From b56b13880e4b2390bb146b07c6a0ca12f8e5dbad Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sun, 11 Oct 2026 18:07:42 +0200 Subject: [PATCH] Stage 0-2 server spine: db, scheduler, REST, auth, economy, map Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map + spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused. Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet. NOT done: military, expansion, social, client, push, deploy docs, bots/admin. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14 --- .gitignore | 7 + docs/API.md | 30 + docs/DECISIONS.md | 35 + DESIGN.md => docs/DESIGN.md | 0 docs/NEXT.md | 11 + docs/openapi.json | 1929 ++++++++++++++++++++++++++++++++ package-lock.json | 55 + package.json | 22 + public/js/data.js | 106 ++ public/js/rules.js | 300 +++++ server/auth.js | 61 + server/clock.js | 17 + server/commands/build.js | 32 + server/commands/cancelBuild.js | 22 + server/commands/index.js | 28 + server/commands/joinWorld.js | 51 + server/commands/renameTown.js | 20 + server/commands/signup.js | 18 + server/db.js | 96 ++ server/errors.js | 43 + server/events/buildDone.js | 15 + server/events/index.js | 5 + server/http.js | 227 ++++ server/index.js | 132 +++ server/migrations/001_init.sql | 120 ++ server/net.js | 274 +++++ server/queries.js | 116 ++ server/routes/auth.js | 61 + server/routes/index.js | 9 + server/routes/map.js | 9 + server/routes/me.js | 12 + server/routes/schemas.js | 43 + server/routes/towns.js | 27 + server/scheduler.js | 95 ++ server/state.js | 78 ++ server/static.js | 181 +++ server/validate.js | 63 ++ server/world.js | 20 + tools/gen-openapi.js | 80 ++ 39 files changed, 4450 insertions(+) create mode 100644 .gitignore create mode 100644 docs/API.md create mode 100644 docs/DECISIONS.md rename DESIGN.md => docs/DESIGN.md (100%) create mode 100644 docs/NEXT.md create mode 100644 docs/openapi.json create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/js/data.js create mode 100644 public/js/rules.js create mode 100644 server/auth.js create mode 100644 server/clock.js create mode 100644 server/commands/build.js create mode 100644 server/commands/cancelBuild.js create mode 100644 server/commands/index.js create mode 100644 server/commands/joinWorld.js create mode 100644 server/commands/renameTown.js create mode 100644 server/commands/signup.js create mode 100644 server/db.js create mode 100644 server/errors.js create mode 100644 server/events/buildDone.js create mode 100644 server/events/index.js create mode 100644 server/http.js create mode 100644 server/index.js create mode 100644 server/migrations/001_init.sql create mode 100644 server/net.js create mode 100644 server/queries.js create mode 100644 server/routes/auth.js create mode 100644 server/routes/index.js create mode 100644 server/routes/map.js create mode 100644 server/routes/me.js create mode 100644 server/routes/schemas.js create mode 100644 server/routes/towns.js create mode 100644 server/scheduler.js create mode 100644 server/state.js create mode 100644 server/static.js create mode 100644 server/validate.js create mode 100644 server/world.js create mode 100644 tools/gen-openapi.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d928533 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +data/ +e2e/out/ +*.db +*.db-wal +*.db-shm +.env diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..3855869 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,30 @@ +# API + +REST JSON under `/api/v1/`. The machine-readable contract is `docs/openapi.json`, generated from the route table +(`npm run openapi`); this file covers conventions and per-resource notes. + +## Conventions + +- Auth: `Authorization: Bearer ` (opaque, one per device; `POST /auth/login` or `/auth/signup` issues one, `POST /auth/logout` + and `DELETE /auth/tokens/:id` revoke). No cookies. +- Every response is an object with `serverTime` (integer ms since epoch, server clock). Clients compute countdowns from the offset. +- Errors: `{ serverTime, error: { code, message, details } }`. Clients switch on `code`. All codes: `x-error-codes` in openapi.json. +- Mutating POSTs accept `Idempotency-Key` (8-64 chars `A-Za-z0-9_.:-`); a replay returns the stored response with `Idempotent-Replay: true`; + the same key with a different request is `idempotency_key_reuse`. +- Lists are cursor-paginated: `?after=&limit=`, response `next` is the cursor or `null`. +- Rate limits: per IP, per token, stricter on login/signup. `429 rate_limited` with `Retry-After`. +- The client never sends computed amounts, only intents. The server recomputes everything with `public/js/rules.js`. + +## Resources (stage 0-2) + +| Route | Purpose | +| ----- | ------- | +| `POST /auth/signup`, `POST /auth/login` | account + token (signup also founds the capital POP) | +| `GET /me` | user, operators (per world), POPs | +| `GET /towns/:id` | full POP state: resources `{amount, rate, cap}` at `serverTime`, power, buildings with the server's build plan, queue | +| `POST /towns/:id/build {key}` | build/upgrade one level of a field (`f1..f18`) or an infrastructure building | +| `DELETE /towns/:id/queue/:eventId` | cancel a running build, 80% refund | +| `GET /map?x&y&r` | rural areas, incumbent sites, POPs in the viewport | +| `GET /notifications?after&limit` | durable notification feed (build done, ...) | + +Later stages append their routes here and to the route table. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 0000000..24ad487 --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,35 @@ +# DECISIONS + +Short log of non-obvious decisions and why. Newest at the bottom. + +## D1 — `node:sqlite` as the driver +Dev machine runs Node 24; the deploy target (Debian 13 LXC) ships Node 22+. `node:sqlite` is used through `server/db.js` only, so +`better-sqlite3` is a one-file swap if it ever misbehaves. Parameters are always positional. + +## D2 — Scheduler processes ALL due events before any command or read +`scheduler.runDue()` runs every pending event with `due_at <= now` globally, in `(due_at, id)` order, not just the ones touching the +town in question. It is simpler and makes fairness trivial (nothing resolves out of order). Cost is nil in practice because the timer +processes events within milliseconds of their due time; it only matters after a restart (catch-up). + +## D3 — One `towns.res_at` for all lazily-grown values +Fiber, hardware, capital, power battery, footprint and loyalty are all settled together at `res_at` (`state.settle`). Any change that alters a +rate (building finished, unit trained or lost) settles first. `rules.resourcesAt` is therefore exact between settles. + +## D4 — Power battery uses the same lazy model +Battery = (amount, rate = net power x world speed, cap = Battery bank). Units are offline while battery = 0 and net < 0 +(`rules.unitsOnline`). The 24 h decommission countdown is an event scheduled from `rules.batteryEmptyAt`. + +## D5 — Rural areas are held by proximity in v1 +DESIGN.md leaves "contested or just held" open. v1: a POP within `ruralReach` (2) tiles of a rural tile gets its +25% (max 3, nearest first). +Computed from the seed, no state. Revisit after the first world. + +## D6 — First world is 101 x 101, not 301 x 301 +DESIGN.md's own open question. `mapRadius` is world data (`worlds.map_radius`), default 50. + +## D7 — `docs/openapi.json` is generated +`tools/gen-openapi.js` builds it from the route table (schemas live in route meta + `server/routes/schemas.js`). `npm test` fails when the +committed file is stale, which satisfies "updated in the same commit as any route change" mechanically. + +## 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). diff --git a/DESIGN.md b/docs/DESIGN.md similarity index 100% rename from DESIGN.md rename to docs/DESIGN.md diff --git a/docs/NEXT.md b/docs/NEXT.md new file mode 100644 index 0000000..38e42fa --- /dev/null +++ b/docs/NEXT.md @@ -0,0 +1,11 @@ +# NEXT + +Honest status, updated at the end of every stage. + +## Done +- Stage 0 skeleton: db + migrations, clock, scheduler with catch-up, router, auth/tokens, error envelope, openapi generation, static server. +- Stage 1 economy (server): lazy resources, buildings, build queue, storage caps, power battery. +- Stage 2 world (server): seeded tiles, spawn ring, map viewport query. + +## Not done +- Everything else. See CLAUDE.md "Working in stages". diff --git a/docs/openapi.json b/docs/openapi.json new file mode 100644 index 0000000..c5d860c --- /dev/null +++ b/docs/openapi.json @@ -0,0 +1,1929 @@ +{ + "openapi": "3.0.3", + "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" + }, + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + "/auth/login": { + "post": { + "summary": "Log in on a device and get a bearer token", + "tags": [ + "auth" + ], + "operationId": "postAuthLogin", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "username", + "password" + ], + "properties": { + "username": { + "type": "string", + "minLength": 3, + "maxLength": 20, + "pattern": "^[A-Za-z0-9_-]+$" + }, + "password": { + "type": "string", + "minLength": 8, + "maxLength": 128 + }, + "device": { + "type": "string", + "maxLength": 40 + } + } + } + } + } + }, + "security": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthResult" + } + } + } + }, + "401": { + "description": "Error codes: invalid_credentials", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Error codes: forbidden", + "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" + } + } + } + } + } + } + }, + "/auth/logout": { + "post": { + "summary": "Revoke the token used for this request", + "tags": [ + "auth" + ], + "operationId": "postAuthLogout", + "parameters": [], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/auth/signup": { + "post": { + "summary": "Create an account, join the world and get a bearer token", + "tags": [ + "auth" + ], + "operationId": "postAuthSignup", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "username", + "password" + ], + "properties": { + "invite": { + "type": "string", + "maxLength": 64 + }, + "worldId": { + "type": "integer", + "minimum": 1 + }, + "username": { + "type": "string", + "minLength": 3, + "maxLength": 20, + "pattern": "^[A-Za-z0-9_-]+$" + }, + "password": { + "type": "string", + "minLength": 8, + "maxLength": 128 + }, + "device": { + "type": "string", + "maxLength": 40 + } + } + } + } + } + }, + "security": [], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthResult" + } + } + } + }, + "403": { + "description": "Error codes: signup_closed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: username_taken, world_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" + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/auth/tokens": { + "get": { + "summary": "List this account's active device tokens", + "tags": [ + "auth" + ], + "operationId": "getAuthTokens", + "parameters": [], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "serverTime", + "tokens" + ], + "properties": { + "serverTime": { + "type": "integer" + }, + "tokens": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Token" + } + } + } + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/auth/tokens/{tokenId}": { + "delete": { + "summary": "Revoke one of this account's tokens", + "tags": [ + "auth" + ], + "operationId": "deleteAuthTokensTokenId", + "parameters": [ + { + "name": "tokenId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/map": { + "get": { + "summary": "Map viewport: rural areas, incumbent sites and POPs within (x±r, y±r); land tiles are implied", + "tags": [ + "map" + ], + "operationId": "getMap", + "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": "r", + "in": "query", + "required": true, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 40 + } + }, + { + "name": "worldId", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MapResponse" + } + } + } + }, + "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", + "tags": [ + "me" + ], + "operationId": "getMe", + "parameters": [], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Me" + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/notifications": { + "get": { + "summary": "Notifications for this user (cursor: after = last seen id)", + "tags": [ + "me" + ], + "operationId": "getNotifications", + "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 + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NotificationList" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "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" + } + } + } + } + } + } + }, + "/towns/{id}": { + "get": { + "summary": "Full state of one of your POPs: resources, power, buildings, build queue", + "tags": [ + "towns" + ], + "operationId": "getTownsId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TownResponse" + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/towns/{id}/build": { + "post": { + "summary": "Build or upgrade a building (fields f1..f18 or an infrastructure building type) by one level", + "tags": [ + "towns" + ], + "operationId": "postTownsIdBuild", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "key" + ], + "properties": { + "key": { + "type": "string", + "maxLength": 32, + "pattern": "^[a-z0-9_]+$" + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BuildResult" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found, unknown_building", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: already_queued, max_level, not_buildable, 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}/queue/{eventId}": { + "delete": { + "summary": "Cancel a running build and get 80% of its cost back", + "tags": [ + "towns" + ], + "operationId": "deleteTownsIdQueueEventId", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "eventId", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" + } + } + } + }, + "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" + } + } + } + } + } + } + }, + "/towns/{id}/rename": { + "post": { + "summary": "Rename a POP", + "tags": [ + "towns" + ], + "operationId": "postTownsIdRename", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "minLength": 2, + "maxLength": 40 + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "serverTime", + "name" + ], + "properties": { + "serverTime": { + "type": "integer" + }, + "name": { + "type": "string" + } + } + } + } + } + }, + "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" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "Cost": { + "type": "object", + "properties": { + "fiber": { + "type": "integer" + }, + "hardware": { + "type": "integer" + }, + "capital": { + "type": "integer" + } + }, + "required": [ + "fiber", + "hardware", + "capital" + ], + "additionalProperties": true + }, + "Error": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "code", + "message", + "details" + ], + "additionalProperties": true + } + }, + "required": [ + "serverTime", + "error" + ], + "additionalProperties": true + }, + "World": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "speed": { + "type": "number" + }, + "mapRadius": { + "type": "integer" + }, + "seed": { + "type": "integer" + }, + "startAt": { + "type": "integer" + }, + "endAt": { + "type": "integer", + "nullable": true + }, + "status": { + "type": "string" + }, + "preset": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "speed", + "mapRadius", + "seed", + "startAt", + "endAt", + "status", + "preset" + ], + "additionalProperties": true + }, + "TownSummary": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "isCapital": { + "type": "boolean" + } + }, + "required": [ + "id", + "name", + "x", + "y", + "isCapital" + ], + "additionalProperties": true + }, + "Operator": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "asNumber": { + "type": "integer" + }, + "allianceId": { + "type": "integer", + "nullable": true + }, + "protectionUntil": { + "type": "integer" + }, + "world": { + "$ref": "#/components/schemas/World" + }, + "towns": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TownSummary" + } + } + }, + "required": [ + "id", + "name", + "asNumber", + "allianceId", + "protectionUntil", + "world", + "towns" + ], + "additionalProperties": true + }, + "Me": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "user": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "username": { + "type": "string" + }, + "createdAt": { + "type": "integer" + } + }, + "required": [ + "id", + "username", + "createdAt" + ], + "additionalProperties": true + }, + "operators": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Operator" + } + } + }, + "required": [ + "serverTime", + "user", + "operators" + ], + "additionalProperties": true + }, + "AuthResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "token": { + "type": "string" + }, + "tokenId": { + "type": "integer" + }, + "user": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "username": { + "type": "string" + } + }, + "required": [ + "id", + "username" + ], + "additionalProperties": true + }, + "operators": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Operator" + } + } + }, + "required": [ + "serverTime", + "token", + "tokenId", + "user", + "operators" + ], + "additionalProperties": true + }, + "Token": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "device": { + "type": "string" + }, + "createdAt": { + "type": "integer" + }, + "lastUsedAt": { + "type": "integer" + }, + "current": { + "type": "boolean" + } + }, + "required": [ + "id", + "device", + "createdAt", + "lastUsedAt", + "current" + ], + "additionalProperties": true + }, + "BuildPlan": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "code": { + "type": "string", + "nullable": true + }, + "toLevel": { + "type": "integer" + }, + "cost": { + "$ref": "#/components/schemas/Cost" + }, + "durationMs": { + "type": "integer" + }, + "missing": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "level": { + "type": "integer" + }, + "have": { + "type": "integer" + } + }, + "required": [ + "type", + "level", + "have" + ], + "additionalProperties": true + } + } + }, + "required": [ + "ok", + "code", + "toLevel" + ], + "additionalProperties": true + }, + "BuildingView": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "type": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "level": { + "type": "integer" + }, + "maxLevel": { + "type": "integer" + }, + "next": { + "$ref": "#/components/schemas/BuildPlan" + } + }, + "required": [ + "key", + "type", + "kind", + "level", + "maxLevel", + "next" + ], + "additionalProperties": true + }, + "QueueEntry": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "key": { + "type": "string" + }, + "type": { + "type": "string" + }, + "toLevel": { + "type": "integer" + }, + "startedAt": { + "type": "integer" + }, + "dueAt": { + "type": "integer" + } + }, + "required": [ + "id", + "key", + "type", + "toLevel", + "startedAt", + "dueAt" + ], + "additionalProperties": true + }, + "ResourceView": { + "type": "object", + "properties": { + "amount": { + "type": "number" + }, + "rate": { + "type": "number" + }, + "cap": { + "type": "number" + } + }, + "required": [ + "amount", + "rate", + "cap" + ], + "additionalProperties": true + }, + "Town": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "isCapital": { + "type": "boolean" + }, + "ownerId": { + "type": "integer" + }, + "worldId": { + "type": "integer" + }, + "loyalty": { + "type": "number" + }, + "footprint": { + "type": "number" + }, + "footprintPerDay": { + "type": "number" + }, + "resources": { + "type": "object", + "properties": { + "fiber": { + "$ref": "#/components/schemas/ResourceView" + }, + "hardware": { + "$ref": "#/components/schemas/ResourceView" + }, + "capital": { + "$ref": "#/components/schemas/ResourceView" + } + }, + "required": [ + "fiber", + "hardware", + "capital" + ], + "additionalProperties": true + }, + "power": { + "type": "object", + "properties": { + "out": { + "type": "number" + }, + "draw": { + "type": "number" + }, + "net": { + "type": "number" + }, + "buffer": { + "type": "number" + }, + "bufferCap": { + "type": "number" + }, + "bufferRate": { + "type": "number" + }, + "online": { + "type": "boolean" + } + }, + "required": [ + "out", + "draw", + "net", + "buffer", + "bufferCap", + "bufferRate", + "online" + ], + "additionalProperties": true + }, + "buildings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BuildingView" + } + }, + "queue": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QueueEntry" + } + }, + "queueSlots": { + "type": "integer" + }, + "bonus": { + "type": "object", + "properties": { + "fiber": { + "type": "number" + }, + "hardware": { + "type": "number" + }, + "capital": { + "type": "number" + } + }, + "required": [ + "fiber", + "hardware", + "capital" + ], + "additionalProperties": true + } + }, + "required": [ + "id", + "name", + "x", + "y", + "isCapital", + "ownerId", + "worldId", + "loyalty", + "footprint", + "footprintPerDay", + "resources", + "power", + "buildings", + "queue", + "queueSlots", + "bonus" + ], + "additionalProperties": true + }, + "TownResponse": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "town": { + "$ref": "#/components/schemas/Town" + } + }, + "required": [ + "serverTime", + "town" + ], + "additionalProperties": true + }, + "MapTown": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "isCapital": { + "type": "boolean" + }, + "owner": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "asNumber": { + "type": "integer" + }, + "allianceId": { + "type": "integer", + "nullable": true + }, + "protected": { + "type": "boolean" + } + }, + "required": [ + "id", + "name", + "asNumber", + "allianceId", + "protected" + ], + "additionalProperties": true + } + }, + "required": [ + "id", + "name", + "x", + "y", + "isCapital", + "owner" + ], + "additionalProperties": true + }, + "MapSpecial": { + "type": "object", + "properties": { + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "bonus": { + "type": "string", + "nullable": true + } + }, + "required": [ + "x", + "y", + "type", + "bonus" + ], + "additionalProperties": true + }, + "MapResponse": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "world": { + "$ref": "#/components/schemas/World" + }, + "bounds": { + "type": "object", + "properties": { + "x0": { + "type": "integer" + }, + "x1": { + "type": "integer" + }, + "y0": { + "type": "integer" + }, + "y1": { + "type": "integer" + } + }, + "required": [ + "x0", + "x1", + "y0", + "y1" + ], + "additionalProperties": true + }, + "specials": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MapSpecial" + } + }, + "towns": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MapTown" + } + } + }, + "required": [ + "serverTime", + "world", + "bounds", + "specials", + "towns" + ], + "additionalProperties": true + }, + "BuildResult": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "eventId": { + "type": "integer" + }, + "key": { + "type": "string" + }, + "type": { + "type": "string" + }, + "toLevel": { + "type": "integer" + }, + "startedAt": { + "type": "integer" + }, + "dueAt": { + "type": "integer" + }, + "cost": { + "$ref": "#/components/schemas/Cost" + } + }, + "required": [ + "serverTime", + "eventId", + "key", + "type", + "toLevel", + "startedAt", + "dueAt", + "cost" + ], + "additionalProperties": true + }, + "Notification": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "type": { + "type": "string" + }, + "worldId": { + "type": "integer", + "nullable": true + }, + "payload": { + "type": "object", + "additionalProperties": true + }, + "createdAt": { + "type": "integer" + }, + "readAt": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "id", + "type", + "worldId", + "payload", + "createdAt", + "readAt" + ], + "additionalProperties": true + }, + "NotificationList": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Notification" + } + }, + "next": { + "type": "integer", + "nullable": true + } + }, + "required": [ + "serverTime", + "items", + "next" + ], + "additionalProperties": true + }, + "Ok": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + } + }, + "required": [ + "serverTime" + ], + "additionalProperties": true + } + }, + "securitySchemes": { + "bearer": { + "type": "http", + "scheme": "bearer", + "description": "Opaque device token from /auth/login or /auth/signup" + } + } + }, + "x-error-codes": { + "bad_request": { + "status": 400, + "description": "The request could not be parsed." + }, + "validation_failed": { + "status": 422, + "description": "A field is missing or has the wrong shape." + }, + "unauthorized": { + "status": 401, + "description": "Missing, invalid or revoked token." + }, + "invalid_credentials": { + "status": 401, + "description": "Wrong username or password." + }, + "forbidden": { + "status": 403, + "description": "You may not do that." + }, + "not_found": { + "status": 404, + "description": "No such thing." + }, + "method_not_allowed": { + "status": 405, + "description": "Wrong HTTP method for this path." + }, + "conflict": { + "status": 409, + "description": "The request conflicts with the current state." + }, + "request_in_progress": { + "status": 409, + "description": "A request with this Idempotency-Key is still running." + }, + "idempotency_key_reuse": { + "status": 422, + "description": "This Idempotency-Key was used for a different request." + }, + "payload_too_large": { + "status": 413, + "description": "Request body too large." + }, + "rate_limited": { + "status": 429, + "description": "Too many requests, slow down." + }, + "internal_error": { + "status": 500, + "description": "Something broke on our side." + }, + "signup_closed": { + "status": 403, + "description": "Signup needs a valid invite code." + }, + "username_taken": { + "status": 409, + "description": "That username is taken." + }, + "world_full": { + "status": 409, + "description": "There is no room left on the map." + }, + "unknown_building": { + "status": 404, + "description": "No such building or slot." + }, + "not_buildable": { + "status": 409, + "description": "That building cannot be built here." + }, + "max_level": { + "status": 409, + "description": "Already at the maximum level." + }, + "requirements_not_met": { + "status": 409, + "description": "A required building level is missing." + }, + "already_queued": { + "status": 409, + "description": "That building is already being built." + }, + "queue_full": { + "status": 409, + "description": "All build slots are busy." + }, + "not_enough_resources": { + "status": 409, + "description": "Not enough resources." + } + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..34fc5d6 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,55 @@ +{ + "name": "upstream", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "upstream", + "version": "0.1.0", + "dependencies": { + "ws": "^8.18.0" + }, + "devDependencies": { + "playwright-core": "^1.49.0" + }, + "engines": { + "node": ">=22.13" + } + }, + "node_modules/playwright-core": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..1d76a34 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "upstream", + "version": "0.1.0", + "description": "UPSTREAM: persistent multiplayer browser strategy game about rival regional network operators", + "private": true, + "main": "server/index.js", + "scripts": { + "start": "node server/index.js", + "test": "node --test test/", + "openapi": "node tools/gen-openapi.js", + "e2e": "node e2e/run.js" + }, + "engines": { + "node": ">=22.13" + }, + "dependencies": { + "ws": "^8.18.0" + }, + "devDependencies": { + "playwright-core": "^1.49.0" + } +} diff --git a/public/js/data.js b/public/js/data.js new file mode 100644 index 0000000..3a64673 --- /dev/null +++ b/public/js/data.js @@ -0,0 +1,106 @@ +'use strict'; +/* + * ALL content and balance for UPSTREAM. Plain data, no logic: rules.js turns it into formulas. + * Loads as a browser script (window.UpstreamData) and as a Node module. Player-facing names live in i18n.js; + * ids here are the generic genre terms used by the code. + * + * Every number is a first-pass starting point for the bot balance runs (stage 7), not a promise. + * Times are in seconds at world speed 1x. Costs are for level 1 and grow with COST_GROWTH. + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.UpstreamData = factory(); +}(typeof self !== 'undefined' ? self : this, function () { + const HOUR_MS = 3600 * 1000; + + // Storable resources. Power is a rate plus a battery buffer, not an accumulating stock. + const RESOURCES = ['fiber', 'hardware', 'capital']; + + const FORMULAS = { + productionBase: 6, // per hour at level 1 + productionGrowth: 1.25, + costGrowth: 1.28, + timeGrowth: 1.16, + storageBase: 1000, // Rack hall level 1 + storageGrowth: 1.22, + batteryBase: 200, // Battery bank level 1, in power points + batteryGrowth: 1.22, + coreSpeedPerLevel: 0.04, // build time / (1 + 0.04 * core router level) + firewallPerLevel: 0.03, // defence multiplier 1 + 0.03 * level + ruralBonus: 0.25, // production bonus per rural area in reach + ruralMax: 3, + ruralReach: 2, // tiles + footprintBase: 1, // per level-step per day: 1 + L / 5 + footprintDivisor: 5, + footprintNeedBase: 500, // need(n) = 500 * n^1.8 for the n-th extra POP + footprintNeedExp: 1.8, + loyaltyRegenPerHour: 1, + loyaltyMax: 100, + secondQueueCoreLevel: 10, // Core router level that opens the second build slot + minBuildMs: 5000, + }; + + // Resource fields: 18 slots per POP, 4 fixed to each production type plus 2 wild slots chosen at founding. + const FIELD_SLOTS = 18; + const FIELD_TYPES = ['cable_yard', 'supply_depot', 'sales_office', 'substation']; + const FIELD_PRODUCES = { cable_yard: 'fiber', supply_depot: 'hardware', sales_office: 'capital', substation: 'power' }; + const FIELDS_PER_TYPE = 4; + const WILD_SLOTS = 2; + + // kind: 'field' | 'infra'. draw: power draw per level. requires: [{ type, level }] (all must hold). + // The key of an infra building is its type; field keys are f1..f18. + const BUILDINGS = { + cable_yard: { kind: 'field', maxLevel: 20, cost: { fiber: 40, hardware: 25, capital: 15 }, time: 120, draw: 0, requires: [] }, + supply_depot: { kind: 'field', maxLevel: 20, cost: { fiber: 45, hardware: 20, capital: 20 }, time: 130, draw: 0, requires: [] }, + sales_office: { kind: 'field', maxLevel: 20, cost: { fiber: 50, hardware: 30, capital: 10 }, time: 140, draw: 0, requires: [] }, + substation: { kind: 'field', maxLevel: 20, cost: { fiber: 35, hardware: 40, capital: 25 }, time: 150, draw: 0, requires: [] }, + + core_router: { kind: 'infra', maxLevel: 20, cost: { fiber: 90, hardware: 70, capital: 60 }, time: 300, draw: 1, requires: [] }, + rack_hall: { kind: 'infra', maxLevel: 20, cost: { fiber: 80, hardware: 50, capital: 40 }, time: 240, draw: 1, requires: [] }, + battery_bank: { kind: 'infra', maxLevel: 20, cost: { fiber: 60, hardware: 80, capital: 40 }, time: 240, draw: 1, requires: [] }, + firewall: { kind: 'infra', maxLevel: 20, cost: { fiber: 100, hardware: 90, capital: 50 }, time: 360, draw: 1, requires: [{ type: 'core_router', level: 2 }] }, + noc: { kind: 'infra', maxLevel: 20, cost: { fiber: 120, hardware: 80, capital: 60 }, time: 360, draw: 1, requires: [{ type: 'core_router', level: 2 }] }, + research_lab: { kind: 'infra', maxLevel: 20, cost: { fiber: 140, hardware: 120, capital: 90 }, time: 420, draw: 1, requires: [{ type: 'core_router', level: 3 }] }, + ops_lab: { kind: 'infra', maxLevel: 20, cost: { fiber: 150, hardware: 130, capital: 80 }, time: 420, draw: 1, requires: [{ type: 'core_router', level: 3 }, { type: 'research_lab', level: 3 }] }, + internet_exchange: { kind: 'infra', maxLevel: 20, cost: { fiber: 130, hardware: 100, capital: 140 }, time: 420, draw: 1, requires: [{ type: 'core_router', level: 4 }] }, + peering_office: { kind: 'infra', maxLevel: 20, cost: { fiber: 110, hardware: 90, capital: 120 }, time: 420, draw: 1, requires: [{ type: 'core_router', level: 5 }] }, + rollout_depot: { kind: 'infra', maxLevel: 20, cost: { fiber: 300, hardware: 250, capital: 250 }, time: 600, draw: 1, requires: [{ type: 'core_router', level: 10 }] }, + // Only buildable on backbone landing sites (end game, stage 5+). Cost is deliberately far above the rest. + backbone_node: { kind: 'infra', maxLevel: 100, cost: { fiber: 4000, hardware: 4000, capital: 4000 }, time: 7200, draw: 0, requires: [], special: 'backbone' }, + }; + + // A brand-new capital POP: fields at level 1, a little infrastructure, some resources. + const START = { + fieldLevel: 1, + infra: { core_router: 1, rack_hall: 1, battery_bank: 1 }, + resources: { fiber: 750, hardware: 750, capital: 750 }, + battery: 100, + loyalty: 100, + // Wild slots: the two wild fields get these types unless the signup picks (stage 1: fixed, stage 4 lets you choose) + wild: ['cable_yard', 'supply_depot'], + }; + + const TILE = { + ruralShare: 0.06, // share of tiles that are rural areas + incumbentShare: 0.02, // share of tiles that are incumbent (NPC) sites + ruralTypes: ['fiber', 'hardware', 'capital'], // which resource a rural area boosts + spawnMinSpacing: 3, + spawnRingStart: 4, // first spawn ring radius (tiles from the centre) + spawnRingStep: 3, + }; + + const PROTECTION_HOURS = 72; + + // AS numbers come from the 32-bit private range (RFC 6996). Display name only. + const AS_RANGE = { min: 4200000000, max: 4294967294 }; + + const WORLD_DEFAULTS = { + name: 'World 1', + speed: 1, + mapRadius: 50, // coordinates -50..50 (101 x 101). DESIGN.md says shrink for the first world. + 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 }; +})); diff --git a/public/js/rules.js b/public/js/rules.js new file mode 100644 index 0000000..5721b49 --- /dev/null +++ b/public/js/rules.js @@ -0,0 +1,300 @@ +'use strict'; +/* + * ALL game rules for UPSTREAM: pure, deterministic, no DOM, no I/O, no Date.now(). `now` and randomness are arguments. + * Loads as a browser script (window.UpstreamRules, needs data.js first) and as a Node module. + * The client uses this for previews; the server recomputes everything and never trusts a client-sent amount. + * + * Time model: every growing quantity is stored as (amount, updatedAt) and its rate follows from the buildings. The + * server settles a town (stores the current value at the new time) before it changes anything that changes a rate. + * Between settles the rate is constant, so `resourcesAt` is exact. + * + * Town shape these functions work on (built by server/state.js, or by the client from an API response): + * { speed, updatedAt, res: { fiber, hardware, capital, battery }, footprint, + * buildings: { [key]: { type, level } }, unitDraw, bonus: { fiber, hardware, capital } } + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js')); + else root.UpstreamRules = factory(root.UpstreamData); +}(typeof self !== 'undefined' ? self : this, function (D) { + const F = D.FORMULAS; + const HOUR = D.HOUR_MS; + const DAY = 24 * HOUR; + + const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k); + + // ------------------------------------------------------------------ seeded randomness + // mulberry32: tiny, fast, good enough for map generation and combat variance. + function rng(seed) { + let a = seed >>> 0; + return function () { + a = (a + 0x6D2B79F5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + } + + // Stable 32-bit hash of a few integers (tile generation: the same (seed, x, y) always gives the same tile). + function hash(a, b, c) { + let h = (a | 0) ^ 0x9E3779B9; + h = Math.imul(h ^ (b | 0), 0x85EBCA6B); + h = Math.imul(h ^ (h >>> 13) ^ (c | 0), 0xC2B2AE35); + h ^= h >>> 16; + h = Math.imul(h, 0x27D4EB2F); + h ^= h >>> 15; + return h >>> 0; + } + + // ------------------------------------------------------------------ geometry + function distance(ax, ay, bx, by) { return Math.hypot(ax - bx, ay - by); } + + // ------------------------------------------------------------------ the map + // Pure function of the world seed: 'land' | 'rural' | 'incumbent' | 'void' (outside the map). A rural tile also + // says which resource it boosts. Towns are not part of this; they live in the database. + function tileAt(seed, radius, x, y) { + if (Math.abs(x) > radius || Math.abs(y) > radius) return { type: 'void' }; + if (Math.abs(x) <= 2 && Math.abs(y) <= 2) return { type: 'land' }; // keep the centre free + const h = hash(seed, x, y) / 4294967296; + if (h < D.TILE.ruralShare) { + const kinds = D.TILE.ruralTypes; + return { type: 'rural', bonus: kinds[hash(seed ^ 0x5bd1e995, x, y) % kinds.length] }; + } + if (h < D.TILE.ruralShare + D.TILE.incumbentShare) return { type: 'incumbent' }; + return { type: 'land' }; + } + + // Rural areas within reach of (x, y): the tiles whose bonus a POP there enjoys. Biggest bonus counts max 3. + function ruralNear(seed, radius, x, y) { + const out = []; + const r = F.ruralReach; + for (let dy = -r; dy <= r; dy++) { + for (let dx = -r; dx <= r; dx++) { + if ((dx || dy) && Math.hypot(dx, dy) <= r) { + const t = tileAt(seed, radius, x + dx, y + dy); + if (t.type === 'rural') out.push({ x: x + dx, y: y + dy, bonus: t.bonus }); + } + } + } + out.sort((a, b) => Math.hypot(a.x - x, a.y - y) - Math.hypot(b.x - x, b.y - y) || a.x - b.x || a.y - b.y); + return out.slice(0, F.ruralMax); + } + + // Production bonus per resource for a POP at (x, y): { fiber, hardware, capital } as 0.25 steps. + function ruralBonus(seed, radius, x, y) { + const b = { fiber: 0, hardware: 0, capital: 0 }; + for (const t of ruralNear(seed, radius, x, y)) b[t.bonus] += F.ruralBonus; + return b; + } + + // Where does the n-th new operator's capital go? Expanding ring around the centre so early joiners are central. + // `occupied(x, y)` tells whether a tile is taken; `n` is the number of towns already in the world. + // Returns {x, y} or null when the map is full. Deterministic for (seed, n, occupancy). + function pickSpawn(seed, radius, n, towns) { + const rand = rng(hash(seed, n, 0x51a3)); + const spacing = D.TILE.spawnMinSpacing; + const near = (x, y) => towns.some((t) => Math.max(Math.abs(t.x - x), Math.abs(t.y - y)) < spacing); + let ring = D.TILE.spawnRingStart + Math.floor(Math.sqrt(n)) * D.TILE.spawnRingStep; + for (; ring <= radius * 1.5 + D.TILE.spawnRingStep; ring += D.TILE.spawnRingStep) { + const lo = Math.max(2, ring - D.TILE.spawnRingStep), hi = Math.min(radius, ring); + for (let attempt = 0; attempt < 60; attempt++) { + const ang = rand() * Math.PI * 2; + const rr = lo + rand() * (hi - lo); + const x = Math.round(Math.cos(ang) * rr), y = Math.round(Math.sin(ang) * rr); + if (tileAt(seed, radius, x, y).type !== 'land') continue; + if (near(x, y)) continue; + return { x, y }; + } + } + return null; + } + + // ------------------------------------------------------------------ buildings + const growth = (base, g, level) => base * Math.pow(g, level - 1); + + function buildingDef(type) { return hasOwn(D.BUILDINGS, type) ? D.BUILDINGS[type] : null; } + + // Keys: infra buildings use their type; fields f1..f18. + const isFieldKey = (key) => /^f([1-9]|1[0-8])$/.test(key); + + // The fields a fresh POP gets: 4 of each type plus the two wild ones. Returns { f1: 'cable_yard', ... }. + function fieldLayout(wild) { + const types = []; + for (const t of D.FIELD_TYPES) for (let i = 0; i < D.FIELDS_PER_TYPE; i++) types.push(t); + for (let i = 0; i < D.WILD_SLOTS; i++) types.push((wild || D.START.wild)[i] || D.START.wild[i]); + const out = {}; + types.forEach((t, i) => { out['f' + (i + 1)] = t; }); + return out; + } + + // Cost to build `type` UP TO `level` (so level 1 is the base cost). + function buildingCost(type, level) { + const def = buildingDef(type); + const out = {}; + for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(F.costGrowth, level - 1)); + return out; + } + + function coreLevel(town) { const c = town.buildings.core_router; return c ? c.level : 0; } + + // Build time in ms to reach `level`. Core router shortens it; world speed divides it. + function buildTimeMs(type, level, core, speed) { + const def = buildingDef(type); + const secs = def.time * Math.pow(F.timeGrowth, level - 1) / (1 + F.coreSpeedPerLevel * core) / (speed || 1); + return Math.max(F.minBuildMs, Math.round(secs * 1000)); + } + + function queueSlots(town) { return coreLevel(town) >= F.secondQueueCoreLevel ? 2 : 1; } + + function storageCap(town) { + const r = town.buildings.rack_hall; + if (!r || r.level < 1) return F.storageBase / 4; // no rack hall: a small floor so the POP is not stuck + return Math.round(F.storageBase * Math.pow(F.storageGrowth, r.level - 1)); + } + + function batteryCap(town) { + const b = town.buildings.battery_bank; + return b && b.level > 0 ? Math.round(F.batteryBase * Math.pow(F.batteryGrowth, b.level - 1)) : 0; + } + + // Per-hour output of one field at `level` (before world speed and bonuses). Level 0 produces nothing. + function fieldOutputPerHour(level) { + return level > 0 ? growth(F.productionBase, F.productionGrowth, level) : 0; + } + + // Rates per hour for a town: production per resource, power out/draw/net. World speed scales production; power is + // a rate of points, so it is not scaled (the battery drains faster in real time on fast worlds instead). + function ratesPerHour(town) { + const speed = town.speed || 1; + const bonus = town.bonus || {}; + const prod = { fiber: 0, hardware: 0, capital: 0 }; + let powerOut = 0, draw = 0; + for (const key of Object.keys(town.buildings)) { + const b = town.buildings[key]; + const def = buildingDef(b.type); + if (!def) continue; + if (def.kind === 'field') { + const out = fieldOutputPerHour(b.level); + const res = D.FIELD_PRODUCES[b.type]; + if (res === 'power') powerOut += out; + else prod[res] += out * speed * (1 + (bonus[res] || 0)); + } else { + draw += def.draw * b.level; + } + } + draw += town.unitDraw || 0; + return { fiber: prod.fiber, hardware: prod.hardware, capital: prod.capital, powerOut, powerDraw: draw, powerNet: powerOut - draw }; + } + + // Current values at `now`, exact while the rates have not changed since town.updatedAt. Caps apply. + function resourcesAt(town, now) { + const dtH = Math.max(0, now - town.updatedAt) / HOUR; + const rates = ratesPerHour(town); + const cap = storageCap(town); + const bcap = batteryCap(town); + const speed = town.speed || 1; + const out = {}; + for (const r of D.RESOURCES) { + // An amount already above the cap (the rack hall was lowered) is kept, it just stops growing. + out[r] = Math.max(0, Math.min(Math.max(cap, town.res[r]), town.res[r] + rates[r] * dtH)); + } + out.battery = Math.max(0, Math.min(bcap, town.res.battery + rates.powerNet * speed * dtH)); + return { amounts: out, caps: { fiber: cap, hardware: cap, capital: cap, battery: bcap }, rates }; + } + + // When will the battery hit zero (ms epoch)? null if it never does at the current rates. Units go offline then. + function batteryEmptyAt(town, now) { + const { amounts, rates } = resourcesAt(town, now); + if (rates.powerNet >= 0) return null; + if (amounts.battery <= 0) return now; + return now + Math.ceil(amounts.battery / (-rates.powerNet * (town.speed || 1)) * HOUR); + } + + // Are units online right now? Offline when the battery is empty and net power is negative. + function unitsOnline(town, now) { + const { amounts, rates } = resourcesAt(town, now); + return !(amounts.battery <= 0 && rates.powerNet < 0); + } + + // Footprint points per day: every building of level L contributes sum over steps l=1..L of (1 + l/5). + function footprintPerDay(town) { + let total = 0; + for (const key of Object.keys(town.buildings)) { + const L = town.buildings[key].level; + total += L * F.footprintBase + (L * (L + 1) / 2) / F.footprintDivisor; + } + return total * (town.speed || 1); + } + + function footprintAt(town, now) { + return town.footprint + footprintPerDay(town) * Math.max(0, now - town.updatedAt) / DAY; + } + + // Footprint an operator needs to found or take over their n-th extra POP (n = 1 for the second POP). + function footprintNeeded(extraTown) { return Math.round(F.footprintNeedBase * Math.pow(extraTown, F.footprintNeedExp)); } + + function loyaltyAt(loyalty, updatedAt, now, speed) { + return Math.min(F.loyaltyMax, loyalty + F.loyaltyRegenPerHour * (speed || 1) * Math.max(0, now - updatedAt) / HOUR); + } + + // ------------------------------------------------------------------ build planning + // The one function both client (preview) and server (command) use to decide whether `key` can be built or + // upgraded now. `pending` = the build events in flight: [{ key }]. `now` is for the resources at that moment. + // Returns { ok, code, key, type, fromLevel, toLevel, cost, durationMs, missing }. + // Codes are the stable API error codes: unknown_building, max_level, requirements_not_met, already_queued, + // queue_full, not_enough_resources, not_buildable. + function buildPlan(town, key, now, pending, typeHint) { + pending = pending || []; + const cur = hasOwn(town.buildings, key) ? town.buildings[key] : null; + let type = cur ? cur.type : null; + if (!type && !isFieldKey(key) && buildingDef(key)) type = key; // an infra building not built yet + if (!type && typeHint && buildingDef(typeHint) && !isFieldKey(key)) type = typeHint; + const base = { ok: false, key, type, fromLevel: cur ? cur.level : 0 }; + const def = type && buildingDef(type); + if (!def) return Object.assign(base, { code: 'unknown_building' }); + if (def.special) return Object.assign(base, { code: 'not_buildable' }); + if (isFieldKey(key) && !cur) return Object.assign(base, { code: 'unknown_building' }); // fields exist from the start + if (!isFieldKey(key) && key !== type) return Object.assign(base, { code: 'unknown_building' }); + const toLevel = base.fromLevel + 1; + base.toLevel = toLevel; + if (toLevel > def.maxLevel) return Object.assign(base, { code: 'max_level' }); + const missing = []; + for (const rq of def.requires) { + const have = town.buildings[rq.type] ? town.buildings[rq.type].level : 0; + if (have < rq.level) missing.push({ type: rq.type, level: rq.level, have }); + } + base.missing = missing; + base.cost = buildingCost(type, toLevel); + base.durationMs = buildTimeMs(type, toLevel, coreLevel(town), town.speed); + if (missing.length) return Object.assign(base, { code: 'requirements_not_met' }); + if (pending.some((p) => p.key === key)) return Object.assign(base, { code: 'already_queued' }); + if (pending.length >= queueSlots(town)) 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; + } + + // The state a brand-new capital POP starts in. `wild` = the two wild field types. + function initialBuildings(wild) { + const layout = fieldLayout(wild); + const out = {}; + for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: D.START.fieldLevel }; + for (const type of Object.keys(D.START.infra)) out[type] = { type, level: D.START.infra[type] }; + return out; + } + + // ------------------------------------------------------------------ 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) { + const hours = dist / (unitSpeed * (worldSpeed || 1)); + return Math.max(10 * 60 * 1000, Math.round(hours * HOUR)); + } + + return { + rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn, + buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap, + fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt, + footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs, + }; +})); diff --git a/server/auth.js b/server/auth.js new file mode 100644 index 0000000..285b3ec --- /dev/null +++ b/server/auth.js @@ -0,0 +1,61 @@ +'use strict'; +/* + * Passwords (scrypt via node:crypto) and opaque bearer tokens (random 32 bytes, only the sha256 stored, one per + * device, listable and revocable). No cookies: the same scheme serves web and mobile. + */ +const crypto = require('crypto'); +const { promisify } = require('util'); +const scrypt = promisify(crypto.scrypt); + +const N = 16384, R = 8, P = 1, KEYLEN = 64; + +async function hashPassword(password) { + const salt = crypto.randomBytes(16); + const key = await scrypt(password, salt, KEYLEN, { N, r: R, p: P }); + return ['scrypt', N, R, P, salt.toString('base64'), key.toString('base64')].join('$'); +} + +// A well-formed hash that matches nothing, used so an unknown username costs the same time as a wrong password. +const DUMMY = ['scrypt', N, R, P, Buffer.alloc(16).toString('base64'), Buffer.alloc(KEYLEN).toString('base64')].join('$'); + +async function verifyPassword(password, stored) { + const s = stored || DUMMY; + const parts = String(s).split('$'); + if (parts.length !== 6 || parts[0] !== 'scrypt') return false; + const salt = Buffer.from(parts[4], 'base64'), want = Buffer.from(parts[5], 'base64'); + const got = await scrypt(password, salt, want.length, { N: Number(parts[1]), r: Number(parts[2]), p: Number(parts[3]) }); + return crypto.timingSafeEqual(got, want) && s !== DUMMY; +} + +const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex'); +const newToken = () => crypto.randomBytes(32).toString('base64url'); + +function createAuth({ db }) { + const touched = new Map(); // tokenId -> last write, so last_used_at is not written on every request + + // Authorization: Bearer -> { user, tokenId } | null + function authenticate(header, now) { + if (typeof header !== 'string') return null; + const m = /^Bearer ([A-Za-z0-9_-]{20,100})$/.exec(header); + if (!m) return null; + const row = db.get(`SELECT t.id AS tid, t.last_used_at AS used, u.id AS uid, u.username AS username, u.banned AS banned + FROM tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.revoked_at IS NULL`, sha256(m[1])); + if (!row || row.banned) return null; + if (now - (touched.get(row.tid) || row.used) > 60000) { + touched.set(row.tid, now); + db.run('UPDATE tokens SET last_used_at = ? WHERE id = ?', now, row.tid); + } + return { user: { id: row.uid, username: row.username }, tokenId: row.tid }; + } + + // Create a token for a user. Returns { token, tokenId }; the plain token is shown exactly once. + function issueToken(userId, device, now) { + const token = newToken(); + const r = db.run('INSERT INTO tokens (user_id, token_hash, device, created_at, last_used_at) VALUES (?, ?, ?, ?, ?)', userId, sha256(token), device || '', now, now); + return { token, tokenId: Number(r.lastInsertRowid) }; + } + + return { authenticate, issueToken, hashPassword, verifyPassword }; +} + +module.exports = { createAuth, hashPassword, verifyPassword, sha256, newToken }; diff --git a/server/clock.js b/server/clock.js new file mode 100644 index 0000000..cb7ab5a --- /dev/null +++ b/server/clock.js @@ -0,0 +1,17 @@ +'use strict'; +/* + * The only place server code reads time. Every other module takes a clock; tests inject FakeClock. + * All times are integer ms since the epoch, UTC. + */ +class RealClock { + now() { return Date.now(); } +} + +class FakeClock { + constructor(start) { this.t = start === undefined ? Date.UTC(2026, 0, 1) : start; } + now() { return this.t; } + set(t) { this.t = t; } + advance(ms) { this.t += ms; return this.t; } +} + +module.exports = { RealClock, FakeClock }; diff --git a/server/commands/build.js b/server/commands/build.js new file mode 100644 index 0000000..6cacb1e --- /dev/null +++ b/server/commands/build.js @@ -0,0 +1,32 @@ +'use strict'; +/* POST /towns/:id/build. Validate ownership and rules (rules.buildPlan), pay, enqueue the completion event. */ +const R = require('../../public/js/rules.js'); +const { GameError } = require('../errors'); +const { loadTown, settle, spend, pendingBuilds } = require('../state'); + +module.exports = function build(ctx, { userId, townId, key }) { + const { db, now, scheduler } = ctx; + const town = ownedTown(db, userId, townId); + settle(db, town, now); + const pending = pendingBuilds(db, town.id); + const plan = R.buildPlan(town, key, now, pending); + if (!plan.ok) { + throw new GameError(plan.code, { key, type: plan.type, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing }); + } + spend(db, town, plan.cost); + const id = scheduler.enqueue({ + worldId: town.worldId, townId: town.id, type: 'buildDone', dueAt: now + plan.durationMs, + payload: { key, type: plan.type, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId }, + }); + return { eventId: id, key, type: plan.type, toLevel: plan.toLevel, startedAt: now, dueAt: now + plan.durationMs, cost: plan.cost }; +}; + +// The town, if the user owns it; otherwise not_found (never reveal that a foreign town exists). +function ownedTown(db, userId, townId) { + const row = db.get(`SELECT t.id FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?`, townId, userId); + const town = row ? loadTown(db, row.id) : null; + if (!town) throw new GameError('not_found', { what: 'town' }); + return town; +} + +module.exports.ownedTown = ownedTown; diff --git a/server/commands/cancelBuild.js b/server/commands/cancelBuild.js new file mode 100644 index 0000000..42b78d1 --- /dev/null +++ b/server/commands/cancelBuild.js @@ -0,0 +1,22 @@ +'use strict'; +/* DELETE /towns/:id/queue/:eventId. Cancels a running build and refunds 80% (rounded down). */ +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { settle } = require('../state'); +const { ownedTown } = require('./build'); + +const REFUND = 0.8; + +module.exports = function cancelBuild(ctx, { userId, townId, eventId }) { + const { db, now } = ctx; + const town = ownedTown(db, userId, townId); + const ev = db.get("SELECT id, payload FROM events WHERE id = ? AND town_id = ? AND type = 'buildDone' AND status = 'pending'", eventId, town.id); + if (!ev) throw new GameError('not_found', { what: 'queue entry' }); + settle(db, town, now); + const cost = JSON.parse(ev.payload).cost || {}; + const cap = require('../../public/js/rules.js').storageCap(town); + for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(cap, town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND)); + db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id); + db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ?", now, ev.id); + return { cancelled: ev.id }; +}; diff --git a/server/commands/index.js b/server/commands/index.js new file mode 100644 index 0000000..c408741 --- /dev/null +++ b/server/commands/index.js @@ -0,0 +1,28 @@ +'use strict'; +/* + * Player commands: one file each, validate + apply in one transaction. `run` first catches the event queue up to now + * (so a town is never touched with an overdue event pending), then runs the command in a transaction, then re-arms the + * scheduler timer because the command may have enqueued events. + */ +const handlers = { + signup: require('./signup'), + joinWorld: require('./joinWorld'), + build: require('./build'), + cancelBuild: require('./cancelBuild'), + renameTown: require('./renameTown'), +}; + +function createCommands({ db, clock, scheduler }) { + function run(name, args) { + const fn = handlers[name]; + if (!fn) throw new Error('unknown command ' + name); + scheduler.runDue(); + const now = clock.now(); + const out = db.tx(() => fn({ db, clock, now, scheduler }, args)); + scheduler.arm(); + return out; + } + return { run, handlers }; +} + +module.exports = { createCommands }; diff --git a/server/commands/joinWorld.js b/server/commands/joinWorld.js new file mode 100644 index 0000000..d398d2d --- /dev/null +++ b/server/commands/joinWorld.js @@ -0,0 +1,51 @@ +'use strict'; +/* Create an operator for a user in a world, with a capital POP placed by the spawn ring. Not a player-facing route + * on its own: signup and `POST /worlds/:id/join` call it. */ +const crypto = require('crypto'); +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { loadWorld } = require('../state'); + +module.exports = function joinWorld(ctx, { userId, worldId }) { + const { db, now } = ctx; + const world = loadWorld(db, worldId); + if (!world || world.status !== 'running') throw new GameError('not_found', { what: 'world' }); + const user = db.get('SELECT id, username FROM users WHERE id = ?', userId); + if (!user) throw new GameError('not_found', { what: 'user' }); + if (db.get('SELECT 1 AS x FROM operators WHERE world_id = ? AND user_id = ?', worldId, userId)) throw new GameError('conflict', { what: 'already joined' }); + + const towns = db.all('SELECT x, y FROM towns WHERE world_id = ?', worldId); + const spot = R.pickSpawn(world.seed, world.map_radius, towns.length, towns); + if (!spot) throw new GameError('world_full'); + + let asn; + for (let i = 0; i < 50; i++) { + asn = crypto.randomInt(D.AS_RANGE.min, D.AS_RANGE.max); + if (!db.get('SELECT 1 AS x FROM operators WHERE world_id = ? AND as_number = ?', worldId, asn)) break; + asn = null; + } + if (!asn) throw new GameError('internal_error'); + + const protectionMs = Math.round(D.PROTECTION_HOURS * D.HOUR_MS / world.speed); + const op = db.run('INSERT INTO operators (world_id, user_id, name, as_number, protection_until, created_at) VALUES (?, ?, ?, ?, ?, ?)', + worldId, userId, user.username, asn, now + protectionMs, now); + const operatorId = Number(op.lastInsertRowid); + + const townId = createTown(db, { worldId, ownerId: operatorId, name: user.username + ' POP 1', x: spot.x, y: spot.y, isCapital: true, now }); + return { operatorId, townId, x: spot.x, y: spot.y, asNumber: asn }; +}; + +// A town with the starting buildings and resources. Also used by expansion (stage 4) with different `start` data. +function createTown(db, { worldId, ownerId, name, x, y, isCapital, now, buildings, res }) { + const start = res || D.START.resources; + const t = db.run(`INSERT INTO towns (world_id, owner_id, name, x, y, is_capital, loyalty, loyalty_at, fiber, hardware, capital, + battery, footprint, res_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`, + worldId, ownerId, name, x, y, isCapital ? 1 : 0, D.START.loyalty, now, start.fiber, start.hardware, start.capital, D.START.battery, now, now); + const id = Number(t.lastInsertRowid); + const b = buildings || R.initialBuildings(); + for (const key of Object.keys(b)) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', id, key, b[key].type, b[key].level); + return id; +} + +module.exports.createTown = createTown; diff --git a/server/commands/renameTown.js b/server/commands/renameTown.js new file mode 100644 index 0000000..5c65ffc --- /dev/null +++ b/server/commands/renameTown.js @@ -0,0 +1,20 @@ +'use strict'; +const { GameError } = require('../errors'); +const { ownedTown } = require('./build'); + +const STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g'); + +// Display-name hygiene: no control or bidi characters, collapsed whitespace, 2..24 characters. +function cleanName(v) { + const s = Array.from(String(v).replace(STRIP, '').replace(/\s+/g, ' ').trim()).slice(0, 24).join('').trim(); + return s; +} + +module.exports = function renameTown(ctx, { userId, townId, name }) { + const town = ownedTown(ctx.db, userId, townId); + const clean = cleanName(name); + if (clean.length < 2) throw new GameError('validation_failed', { errors: [{ path: 'name', message: 'too short' }] }); + ctx.db.run('UPDATE towns SET name = ? WHERE id = ?', clean, town.id); + return { name: clean }; +}; +module.exports.cleanName = cleanName; diff --git a/server/commands/signup.js b/server/commands/signup.js new file mode 100644 index 0000000..7f5c5a6 --- /dev/null +++ b/server/commands/signup.js @@ -0,0 +1,18 @@ +'use strict'; +/* Create account + operator + capital POP + first token in one transaction. The password hash and token hash are + * computed by the route before the transaction (scrypt is async, a transaction never spans an await). */ +const { GameError } = require('../errors'); +const joinWorld = require('./joinWorld'); + +module.exports = function signup(ctx, { username, passHash, tokenHash, device, worldId }) { + const { db, now } = ctx; + if (db.get('SELECT 1 AS x FROM users WHERE username = ?', username)) throw new GameError('username_taken'); + const w = worldId !== undefined ? db.get("SELECT id FROM worlds WHERE id = ? AND status = 'running'", worldId) + : db.get("SELECT id FROM worlds WHERE status = 'running' ORDER BY id LIMIT 1"); + if (!w) throw new GameError('not_found', { what: 'world' }); + const u = db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', username, passHash, now); + const userId = Number(u.lastInsertRowid); + const joined = joinWorld(ctx, { userId, worldId: w.id }); + const t = db.run('INSERT INTO tokens (user_id, token_hash, device, created_at, last_used_at) VALUES (?, ?, ?, ?, ?)', userId, tokenHash, device || '', now, now); + return Object.assign({ userId, tokenId: Number(t.lastInsertRowid) }, joined); +}; diff --git a/server/db.js b/server/db.js new file mode 100644 index 0000000..73ada02 --- /dev/null +++ b/server/db.js @@ -0,0 +1,96 @@ +'use strict'; +/* + * The only module that touches SQLite. Wraps node:sqlite so the driver can be swapped for better-sqlite3 by + * rewriting this file. One connection, owned by the one Node process, WAL mode. + * + * const db = openDb('./data/game.db'); + * migrate(db); + * db.tx(() => { db.run('INSERT ...', a, b); return db.get('SELECT ...', id); }); + * + * Parameters are always positional (`?`), never interpolated. `tx` nests through savepoints. + */ +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { DatabaseSync } = require('node:sqlite'); + +class Db { + constructor(file) { + this.file = file; + if (file !== ':memory:') fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true }); + this.raw = new DatabaseSync(file); + this.raw.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;'); + this.cache = new Map(); + this.depth = 0; + } + + stmt(sql) { + let s = this.cache.get(sql); + if (!s) { s = this.raw.prepare(sql); this.cache.set(sql, s); } + return s; + } + + static params(p) { return p.map((v) => (v === undefined ? null : v)); } + + run(sql, ...p) { return this.stmt(sql).run(...Db.params(p)); } + get(sql, ...p) { return this.stmt(sql).get(...Db.params(p)); } + all(sql, ...p) { return this.stmt(sql).all(...Db.params(p)); } + exec(sql) { this.raw.exec(sql); } + + // Runs fn inside a transaction (BEGIN IMMEDIATE at the top level, a savepoint when nested). Rolls back and + // rethrows on any exception. fn must be synchronous: a transaction never spans an await. + tx(fn) { + const top = this.depth === 0; + const sp = 'sp' + this.depth; + this.raw.exec(top ? 'BEGIN IMMEDIATE' : 'SAVEPOINT ' + sp); + this.depth++; + let out; + try { + out = fn(); + if (out && typeof out.then === 'function') throw new Error('db.tx callback must not be async'); + } catch (err) { + this.depth--; + this.raw.exec(top ? 'ROLLBACK' : 'ROLLBACK TO ' + sp + '; RELEASE ' + sp); + throw err; + } + this.depth--; + this.raw.exec(top ? 'COMMIT' : 'RELEASE ' + sp); + return out; + } + + // Consistent snapshot into a new file (docs/DEPLOY.md: a systemd timer calls tools/admin.js backup). + backup(dest) { + if (fs.existsSync(dest)) throw new Error('backup target exists: ' + dest); + this.raw.exec("VACUUM INTO '" + dest.replace(/'/g, "''") + "'"); + } + + close() { this.cache.clear(); this.raw.close(); } +} + +function openDb(file) { return new Db(file); } + +// Applies server/migrations/NNN_name.sql in order. Applied migrations are recorded with a checksum: editing one +// after the fact is an error ("never edited after merge"). +function migrate(db, dir) { + dir = dir || path.join(__dirname, 'migrations'); + db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, sha TEXT NOT NULL, applied_at INTEGER NOT NULL)'); + const files = fs.readdirSync(dir).filter((f) => /^\d+.*\.sql$/.test(f)).sort(); + const applied = []; + for (const f of files) { + const sql = fs.readFileSync(path.join(dir, f), 'utf8'); + const sha = crypto.createHash('sha256').update(sql).digest('hex'); + const row = db.get('SELECT sha FROM schema_migrations WHERE name = ?', f); + if (row) { + if (row.sha !== sha) throw new Error('migration ' + f + ' was edited after it was applied'); + continue; + } + db.tx(() => { + db.exec(sql); + db.run('INSERT INTO schema_migrations (name, sha, applied_at) VALUES (?, ?, ?)', f, sha, Date.now()); + }); + applied.push(f); + } + return applied; +} + +module.exports = { openDb, migrate, Db }; diff --git a/server/errors.js b/server/errors.js new file mode 100644 index 0000000..4126426 --- /dev/null +++ b/server/errors.js @@ -0,0 +1,43 @@ +'use strict'; +/* + * Stable API error codes. Clients switch on `code`, never on `message`. Every code the API can return is listed + * here with its HTTP status; docs/API.md and openapi.json are generated from this table. + */ +const CODES = { + bad_request: [400, 'The request could not be parsed.'], + validation_failed: [422, 'A field is missing or has the wrong shape.'], + unauthorized: [401, 'Missing, invalid or revoked token.'], + invalid_credentials: [401, 'Wrong username or password.'], + forbidden: [403, 'You may not do that.'], + not_found: [404, 'No such thing.'], + method_not_allowed: [405, 'Wrong HTTP method for this path.'], + conflict: [409, 'The request conflicts with the current state.'], + request_in_progress: [409, 'A request with this Idempotency-Key is still running.'], + idempotency_key_reuse: [422, 'This Idempotency-Key was used for a different request.'], + payload_too_large: [413, 'Request body too large.'], + rate_limited: [429, 'Too many requests, slow down.'], + internal_error: [500, 'Something broke on our side.'], + signup_closed: [403, 'Signup needs a valid invite code.'], + username_taken: [409, 'That username is taken.'], + world_full: [409, 'There is no room left on the map.'], + // game rules + unknown_building: [404, 'No such building or slot.'], + not_buildable: [409, 'That building cannot be built here.'], + max_level: [409, 'Already at the maximum level.'], + requirements_not_met: [409, 'A required building level is missing.'], + already_queued: [409, 'That building is already being built.'], + queue_full: [409, 'All build slots are busy.'], + not_enough_resources: [409, 'Not enough resources.'], +}; + +class GameError extends Error { + constructor(code, details, message) { + const def = CODES[code]; + super(message || (def ? def[1] : code)); + this.code = code; + this.status = def ? def[0] : 400; + this.details = details || {}; + } +} + +module.exports = { CODES, GameError }; diff --git a/server/events/buildDone.js b/server/events/buildDone.js new file mode 100644 index 0000000..94c4c21 --- /dev/null +++ b/server/events/buildDone.js @@ -0,0 +1,15 @@ +'use strict'; +/* A building level finished. Payload: { key, type, toLevel, userId }. Idempotent: a level never goes down. */ +const { loadTown, settle } = require('../state'); + +module.exports = function buildDone(ctx, ev) { + const { db } = ctx; + const { key, type, toLevel, userId } = ev.payload; + const town = loadTown(db, ev.townId); + if (!town) return; + settle(db, town, ev.dueAt); // values up to the moment of completion, at the OLD rates + 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); + if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel }); +}; diff --git a/server/events/index.js b/server/events/index.js new file mode 100644 index 0000000..db31347 --- /dev/null +++ b/server/events/index.js @@ -0,0 +1,5 @@ +'use strict'; +/* Event type -> handler. One file per event type. */ +module.exports = { + buildDone: require('./buildDone'), +}; diff --git a/server/http.js b/server/http.js new file mode 100644 index 0000000..a41834f --- /dev/null +++ b/server/http.js @@ -0,0 +1,227 @@ +'use strict'; +/* + * Tiny REST layer on node:http: router, JSON in/out, error envelope, bearer auth, rate limits, Idempotency-Key. + * + * const api = createApi({ db, clock, log, opts, services }); + * routes.register(api.router, services); + * server.on('request', (req, res) => url.startsWith('/api/') ? api.handle(req, res) : serveStatic(req, res)); + * + * Route meta (also the source of docs/openapi.json, see tools/gen-openapi.js): + * { summary, tag, auth: true|false, query: schema, body: schema, response: schema, errors: [codes], limit: 'auth' } + * Every JSON response is an object carrying `serverTime`. Errors are { error: { code, message, details } }. + */ +const crypto = require('crypto'); +const { GameError, CODES } = require('./errors'); +const { validate } = require('./validate'); +const { TokenBucket, clientIp } = require('./net'); +const { applySecurityHeaders } = require('./static'); + +const MAX_BODY = 32 * 1024; +const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId']); + +// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound. +class Limiter { + constructor(ratePerSec, burst, maxKeys) { this.rate = ratePerSec; this.burst = burst; this.maxKeys = maxKeys || 20000; this.m = new Map(); } + take(key) { + let b = this.m.get(key); + if (!b) { + if (this.m.size >= this.maxKeys) this.prune(); + b = new TokenBucket(this.rate, this.burst); this.m.set(key, b); + } + return b.take(); + } + prune() { + for (const [k, b] of this.m) if (b.tokens >= b.burst - 0.5) this.m.delete(k); + if (this.m.size >= this.maxKeys) this.m.clear(); // under attack from >maxKeys distinct keys: forget, do not grow + } +} + +class Router { + constructor() { this.routes = []; } + // path like '/towns/:id/build' (relative to /api/v1) + add(method, path, meta, handler) { + const names = []; + const re = new RegExp('^' + path.replace(/:([A-Za-z]+)/g, (m, n) => { names.push(n); return '([^/]+)'; }) + '$'); + this.routes.push({ method, path, re, names, meta: meta || {}, handler }); + } + get(path, meta, h) { this.add('GET', path, meta, h); } + post(path, meta, h) { this.add('POST', path, meta, h); } + del(path, meta, h) { this.add('DELETE', path, meta, h); } + // -> { route, params } | { methods: [...] } (path matches, method does not) | null + find(method, pathname) { + const allowed = []; + for (const r of this.routes) { + const m = r.re.exec(pathname); + if (!m) continue; + if (r.method !== method) { allowed.push(r.method); continue; } + const params = {}; + for (let i = 0; i < r.names.length; i++) { + let v; + try { v = decodeURIComponent(m[i + 1]); } catch (e) { return null; } + if (INT_PARAMS.has(r.names[i])) { + if (!/^\d{1,12}$/.test(v)) return null; + v = Number(v); + } + params[r.names[i]] = v; + } + return { route: r, params }; + } + return allowed.length ? { methods: allowed } : null; + } +} + +// A handler returns a plain object (HTTP 200) or reply(status, object). +class Reply { constructor(status, body) { this.status = status; this.body = body; } } +const reply = (status, body) => new Reply(status, body); + +function createApi({ db, clock, log, opts, auth }) { + const router = new Router(); + const ipLimit = new Limiter(opts.ipRate || 30, opts.ipBurst || 90); + const tokenLimit = new Limiter(opts.tokenRate || 15, opts.tokenBurst || 45); + const authLimit = new Limiter(opts.authRate || 0.1, opts.authBurst || 8); // login / signup: ~1 per 10 s sustained + const inflight = new Set(); + + function send(res, status, body, extra) { + const text = JSON.stringify(body); + applySecurityHeaders(res); + res.writeHead(status, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text), 'Cache-Control': 'no-store' }, extra)); + res.end(text); + } + + function fail(res, err, ctx) { + let ge = err; + if (!(err instanceof GameError)) { + log('internal error ' + (ctx || '') + ': ' + (err && err.stack || err)); + ge = new GameError('internal_error'); + } + const extra = ge.status === 429 && ge.details.retryAfter ? { 'Retry-After': String(ge.details.retryAfter) } : undefined; + send(res, ge.status, { serverTime: clock.now(), error: { code: ge.code, message: ge.message, details: ge.details } }, extra); + } + + function readBody(req) { + return new Promise((resolve, reject) => { + const len = Number(req.headers['content-length'] || 0); + if (len > MAX_BODY) return reject(new GameError('payload_too_large')); + const chunks = []; let size = 0; + req.on('data', (c) => { + size += c.length; + if (size > MAX_BODY) { reject(new GameError('payload_too_large')); req.destroy(); return; } + chunks.push(c); + }); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', () => reject(new GameError('bad_request'))); + }); + } + + async function handle(req, res) { + const ip = clientIp(req, opts.trustProxy, opts.trustedProxies); + const started = clock.now(); + let pathname = '', routeKey = ''; + try { + const u = new URL(req.url, 'http://x'); + pathname = u.pathname; + if (!ipLimit.take(ip)) { log('refused rate_limited(ip) ip=' + ip + ' path=' + pathname); throw new GameError('rate_limited', { retryAfter: 1 }); } + if (!pathname.startsWith('/api/v1/')) throw new GameError('not_found'); + const found = router.find(req.method, pathname.slice('/api/v1'.length)); + if (!found) throw new GameError('not_found'); + if (found.methods) { const e = new GameError('method_not_allowed', { allowed: found.methods }); throw e; } + const { route, params } = found; + routeKey = route.method + ' ' + route.path; + const meta = route.meta; + + if (meta.limit === 'auth' && !authLimit.take(ip)) { log('refused rate_limited(auth) ip=' + ip + ' route=' + routeKey); throw new GameError('rate_limited', { retryAfter: 10 }); } + + let user = null, tokenId = null; + if (meta.auth !== false) { + const a = auth.authenticate(req.headers.authorization, clock.now()); + if (!a) { log('refused unauthorized ip=' + ip + ' route=' + routeKey); throw new GameError('unauthorized'); } + user = a.user; tokenId = a.tokenId; + if (!tokenLimit.take('t' + tokenId)) { log('refused rate_limited(token) token=' + tokenId + ' route=' + routeKey); throw new GameError('rate_limited', { retryAfter: 1 }); } + } + + // query + const query = {}; + for (const [k, v] of u.searchParams) query[k] = v; + let q = {}; + if (meta.query) { + const v = validate(meta.query, query, { coerce: true }); + if (!v.ok) throw new GameError('validation_failed', { errors: v.errors }); + q = v.value; + } + + // body + let body = {}; + if (meta.body) { + const raw = await readBody(req); + let parsed = {}; + if (raw.length) { + if (!/^application\/json\b/i.test(req.headers['content-type'] || '')) throw new GameError('bad_request', { reason: 'content-type must be application/json' }); + try { parsed = JSON.parse(raw.toString('utf8')); } catch (e) { throw new GameError('bad_request', { reason: 'invalid JSON' }); } + } + const v = validate(meta.body, parsed); + if (!v.ok) throw new GameError('validation_failed', { errors: v.errors }); + body = v.value; + } else if (req.method !== 'GET' && req.method !== 'HEAD') { + await readBody(req).catch(() => null); // drain + } + + const ctx = { req, ip, user, tokenId, params, query: q, body, now: clock.now() }; + + // Idempotency-Key on mutating POSTs of authenticated users + const idem = req.method === 'POST' && user ? req.headers['idempotency-key'] : undefined; + let idemId = null; + if (idem !== undefined) { + if (typeof idem !== 'string' || !/^[A-Za-z0-9_.:-]{8,64}$/.test(idem)) throw new GameError('validation_failed', { errors: [{ path: 'Idempotency-Key', message: 'must be 8-64 of A-Za-z0-9_.:-' }] }); + const sig = req.method + ' ' + pathname + ' ' + crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex'); + idemId = user.id + ':' + idem; + const row = db.get('SELECT request, status, body FROM idempotency WHERE user_id = ? AND key = ?', user.id, idem); + if (row) { + if (row.request !== sig) throw new GameError('idempotency_key_reuse'); + return send(res, row.status, JSON.parse(row.body), { 'Idempotent-Replay': 'true' }); + } + if (inflight.has(idemId)) throw new GameError('request_in_progress'); + inflight.add(idemId); + ctx.idem = { key: idem, sig }; + } + try { + let out; + let status = 200; + try { + out = await route.handler(ctx); + if (out instanceof Reply) { status = out.status; out = out.body; } + out = Object.assign({ serverTime: clock.now() }, out); + } catch (err) { + if (ctx.idem && err instanceof GameError && err.status < 500) { + // Replaying a rejected request must give the same rejection, not run it again. + const eb = { serverTime: clock.now(), error: { code: err.code, message: err.message, details: err.details } }; + storeIdem(user.id, ctx.idem, err.status, eb); + } + throw err; + } + if (ctx.idem) storeIdem(user.id, ctx.idem, status, out); + send(res, status, out); + } finally { if (idemId) inflight.delete(idemId); } + } catch (err) { + if (!(err instanceof GameError)) log('request failed ' + routeKey + ' ' + pathname + ': ' + (err && err.stack || err)); + else if (err.status >= 400 && err.code !== 'not_found' && err.code !== 'unauthorized' && err.status !== 429) { + // game-rule refusals are normal traffic; keep them out of the log except for the security-relevant codes + if (err.code === 'forbidden' || err.code === 'validation_failed' || err.code === 'bad_request') log('refused ' + err.code + ' ip=' + ip + ' route=' + routeKey); + } + if (!res.headersSent) fail(res, err, routeKey); + } + } + + function storeIdem(userId, idem, status, body) { + try { + db.run('INSERT OR IGNORE INTO idempotency (user_id, key, request, status, body, created_at) VALUES (?, ?, ?, ?, ?, ?)', userId, idem.key, idem.sig, status, JSON.stringify(body), clock.now()); + } catch (e) { log('could not store idempotency key: ' + e.message); } + } + + function pruneIdempotency() { + db.run('DELETE FROM idempotency WHERE created_at < ?', clock.now() - 24 * 3600 * 1000); + } + + return { router, handle, pruneIdempotency, CODES }; +} + +module.exports = { createApi, Router, Reply, reply, Limiter }; diff --git a/server/index.js b/server/index.js new file mode 100644 index 0000000..8e21327 --- /dev/null +++ b/server/index.js @@ -0,0 +1,132 @@ +'use strict'; +/* + * UPSTREAM server: static client + REST API under /api/v1 + (stage 6) WebSocket push, one SQLite file. + * See docs/API.md, docs/DEPLOY.md. + * + * const { createServer } = require('./server'); + * const srv = await createServer({ port: 8080, dbPath: './data/game.db' }); // srv.port, srv.close(), srv.db, ... + * + * Run directly: PORT=8080 HOST=:: DB_PATH=./data/game.db TRUST_PROXY=auto ALLOWED_ORIGINS=https://game.example.com node server/index.js + */ +const http = require('http'); +const path = require('path'); +const { openDb, migrate } = require('./db'); +const { RealClock } = require('./clock'); +const { Scheduler } = require('./scheduler'); +const { createCommands } = require('./commands'); +const { createQueries } = require('./queries'); +const { createApi } = require('./http'); +const { createAuth } = require('./auth'); +const { ensureWorld } = require('./world'); +const routes = require('./routes'); +const eventHandlers = require('./events'); +const { createStaticHandler, applySecurityHeaders } = require('./static'); +const { parseTrustProxy, parseTrustedProxies, listenDual, listUrls } = require('./net'); + +function defaultLog(msg) { console.log(new Date().toISOString() + ' ' + msg); } + +async function createServer(userOpts) { + const o = { + port: 8080, host: '::', publicDir: path.join(__dirname, '..', 'public'), dbPath: process.env.DB_PATH || './data/game.db', + trustProxy: 'auto', trustedProxies: null, allowedOrigins: [], maxConnPerIp: 40, log: defaultLog, + clock: null, autoArm: true, signupCode: process.env.SIGNUP_CODE || '', + world: { speed: Number(process.env.WORLD_SPEED) || undefined, mapRadius: Number(process.env.WORLD_RADIUS) || undefined, name: process.env.WORLD_NAME || undefined }, + }; + for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k]; + o.trustProxy = parseTrustProxy(o.trustProxy); + o.trustedProxies = parseTrustedProxies(o.trustedProxies); + const log = typeof o.log === 'function' ? o.log : () => {}; + const clock = o.clock || new RealClock(); + + const db = openDb(o.dbPath); + const applied = migrate(db); + if (applied.length) log('applied migrations: ' + applied.join(', ')); + const worldId = ensureWorld(db, clock.now(), o.world); + if (worldId) log('created world ' + worldId); + + const scheduler = new Scheduler({ db, clock, handlers: eventHandlers, log, autoArm: o.autoArm }); + const caught = scheduler.catchUp(); // everything overdue, in order, before accepting traffic + if (caught) log('caught up ' + caught + ' overdue event(s)'); + const commands = createCommands({ db, clock, scheduler }); + const queries = createQueries({ db, clock, scheduler }); + const auth = createAuth({ db }); + const api = createApi({ db, clock, log, opts: o, auth }); + const services = { db, clock, scheduler, commands, queries, auth, opts: o, log }; + routes.register(api.router, services); + api.services = services; + + const serveStatic = createStaticHandler(o.publicDir); + const server = http.createServer((req, res) => { + const url = req.url || '/'; + if (url === '/healthz' || url.startsWith('/healthz?')) { + applySecurityHeaders(res); + res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }); + return res.end(req.method === 'HEAD' ? undefined : 'ok'); + } + if (url.startsWith('/api/')) return api.handle(req, res); + return serveStatic(req, res).catch((err) => { log('static error: ' + (err && err.message)); if (!res.headersSent) res.writeHead(500); res.end(); }); + }); + server.headersTimeout = 20000; server.requestTimeout = 30000; server.keepAliveTimeout = 5000; + const sockets = new Set(); + server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); }); + + const bound = await listenDual(server, o.port, o.host, log); + const port = server.address().port; + scheduler.arm(); + const idemTimer = setInterval(() => { try { api.pruneIdempotency(); } catch (e) { log('prune failed: ' + e.message); } }, 3600 * 1000); + idemTimer.unref(); + + let closePromise = null; + function close() { + if (closePromise) return closePromise; + closePromise = (async () => { + scheduler.stop(); clearInterval(idemTimer); + await new Promise((r) => { server.close(() => r()); if (server.closeIdleConnections) server.closeIdleConnections(); setTimeout(() => { for (const s of sockets) s.destroy(); }, 1000).unref(); }); + db.close(); + })(); + return closePromise; + } + + return Object.assign(services, { port, host: bound, server, api, close, options: o }); +} + +function envInt(name, def) { + const v = process.env[name]; + if (v === undefined || v === '') return def; + const n = Number(v); + if (!Number.isInteger(n) || n < 0) throw new Error(name + ' must be a non-negative integer (got ' + JSON.stringify(v) + ')'); + return n; +} + +async function main() { + const opts = { + port: envInt('PORT', 8080), host: process.env.HOST || '::', + trustProxy: process.env.TRUST_PROXY || 'auto', trustedProxies: process.env.TRUSTED_PROXIES || '', + allowedOrigins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean), + }; + if (process.env.MAX_CONN_PER_IP) opts.maxConnPerIp = envInt('MAX_CONN_PER_IP', 40); + const srv = await createServer(opts); + console.log('UPSTREAM is listening on ' + (srv.host.includes(':') ? '[' + srv.host + ']' : srv.host) + ':' + srv.port + + (srv.host === '::' ? ' (dual stack: IPv4 + IPv6)' : srv.host === '0.0.0.0' ? ' (IPv4 only)' : '')); + console.log(' database: ' + path.resolve(srv.options.dbPath)); + console.log('Open:'); + for (const u of listUrls(srv.host, srv.port)) console.log(' ' + u); + + let stopping = false; + const stop = (sig) => { + if (stopping) { console.log('second ' + sig + ', exiting now'); process.exit(0); } + stopping = true; + console.log('received ' + sig + ', shutting down'); + const force = setTimeout(() => { console.log('shutdown timed out, exiting'); process.exit(0); }, 5000); + force.unref(); + srv.close().then(() => process.exit(0), (err) => { console.error(err); process.exit(0); }); + }; + process.on('SIGINT', () => stop('SIGINT')); + process.on('SIGTERM', () => stop('SIGTERM')); +} + +module.exports = { createServer }; + +if (require.main === module) { + main().catch((err) => { console.error('UPSTREAM failed to start: ' + (err && err.message || err)); process.exit(1); }); +} diff --git a/server/migrations/001_init.sql b/server/migrations/001_init.sql new file mode 100644 index 0000000..ed3d592 --- /dev/null +++ b/server/migrations/001_init.sql @@ -0,0 +1,120 @@ +-- Stage 0/1/2 schema: worlds, accounts, tokens, operators, towns, buildings, the event queue. +-- Every game row carries world_id. Times are integer ms since the epoch (UTC). + +CREATE TABLE worlds ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + speed REAL NOT NULL DEFAULT 1, + map_radius INTEGER NOT NULL, + seed INTEGER NOT NULL, + start_at INTEGER NOT NULL, + end_at INTEGER, + status TEXT NOT NULL DEFAULT 'running', -- running | ended + preset TEXT NOT NULL DEFAULT 'standard', + config TEXT NOT NULL DEFAULT '{}', + created_at INTEGER NOT NULL +); + +CREATE TABLE users ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + pass_hash TEXT NOT NULL, + banned INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); + +-- Opaque bearer tokens, one per device. Only the sha256 of the token is stored. +CREATE TABLE tokens ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id), + token_hash TEXT NOT NULL UNIQUE, + device TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + last_used_at INTEGER NOT NULL, + revoked_at INTEGER +); +CREATE INDEX tokens_user ON tokens(user_id); + +-- A user's presence in one world. +CREATE TABLE operators ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL REFERENCES worlds(id), + user_id INTEGER NOT NULL REFERENCES users(id), + name TEXT NOT NULL, + as_number INTEGER NOT NULL, + alliance_id INTEGER, + protection_until INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + UNIQUE (world_id, user_id), + UNIQUE (world_id, as_number) +); + +-- A POP. Growing quantities are (amount, res_at): current value = rules.resourcesAt(town, now). +CREATE TABLE towns ( + id INTEGER PRIMARY KEY, + world_id INTEGER NOT NULL REFERENCES worlds(id), + owner_id INTEGER NOT NULL REFERENCES operators(id), + name TEXT NOT NULL, + x INTEGER NOT NULL, + y INTEGER NOT NULL, + is_capital INTEGER NOT NULL DEFAULT 0, + loyalty REAL NOT NULL DEFAULT 100, + loyalty_at INTEGER NOT NULL, + fiber REAL NOT NULL, + hardware REAL NOT NULL, + capital REAL NOT NULL, + battery REAL NOT NULL, + footprint REAL NOT NULL DEFAULT 0, + res_at INTEGER NOT NULL, + created_at INTEGER NOT NULL, + UNIQUE (world_id, x, y) +); +CREATE INDEX towns_owner ON towns(owner_id); + +-- key: 'f1'..'f18' for resource fields, the building type for infrastructure. +CREATE TABLE buildings ( + town_id INTEGER NOT NULL REFERENCES towns(id), + key TEXT NOT NULL, + type TEXT NOT NULL, + level INTEGER NOT NULL, + PRIMARY KEY (town_id, key) +); + +-- Every future thing is a row here; scheduler.js processes them in (due_at, id) order. +CREATE TABLE events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + world_id INTEGER NOT NULL, + due_at INTEGER NOT NULL, + type TEXT NOT NULL, + town_id INTEGER, -- the main town the event is about (queue listings) + payload TEXT NOT NULL DEFAULT '{}', + status TEXT NOT NULL DEFAULT 'pending', -- pending | done | failed | cancelled + created_at INTEGER NOT NULL, + done_at INTEGER, + error TEXT +); +CREATE INDEX events_due ON events(status, due_at, id); +CREATE INDEX events_town ON events(town_id, status); + +-- Written by event handlers so APNs/FCM push can be added later without touching game logic. +CREATE TABLE notifications ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id), + world_id INTEGER, + type TEXT NOT NULL, + payload TEXT NOT NULL DEFAULT '{}', + created_at INTEGER NOT NULL, + read_at INTEGER +); +CREATE INDEX notifications_user ON notifications(user_id, id); + +-- Idempotency-Key replay store for mutating POSTs. +CREATE TABLE idempotency ( + user_id INTEGER NOT NULL, + key TEXT NOT NULL, + request TEXT NOT NULL, + status INTEGER NOT NULL, + body TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (user_id, key) +); diff --git a/server/net.js b/server/net.js new file mode 100644 index 0000000..4584657 --- /dev/null +++ b/server/net.js @@ -0,0 +1,274 @@ +'use strict'; +/* + * Networking helpers: client IP / reverse-proxy awareness, Origin check, token bucket, + * dual-stack listen and the "what URLs can I open" list for the start-up banner. + * No dependencies beyond Node core. + */ +const net = require('net'); +const os = require('os'); +const { performance } = require('perf_hooks'); + +// ---------------------------------------------------------------- addresses +// "::ffff:1.2.3.4" -> "1.2.3.4"; strips an IPv6 zone ("fe80::1%eth0"); lower-cases. +function normalizeIp(addr) { + if (typeof addr !== 'string') return ''; + let a = addr.trim().toLowerCase(); + const z = a.indexOf('%'); + if (z >= 0) a = a.slice(0, z); + if (a.startsWith('::ffff:') && net.isIPv4(a.slice(7))) a = a.slice(7); + return a; +} + +// Loopback, RFC1918, link-local, unique-local (fc00::/7) and the unspecified address. +function isPrivateIp(addr) { + const ip = normalizeIp(addr); + if (net.isIPv4(ip)) { + const [a, b] = ip.split('.').map(Number); + return a === 127 || a === 10 || a === 0 || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 169 && b === 254); + } + if (net.isIPv6(ip)) { + if (ip === '::1' || ip === '::') return true; + const first = ip.startsWith('::') ? 0 : parseInt(ip.split(':')[0], 16); + if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7 + if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10 + } + return false; +} + +// 'auto' | true | false, also from env-style strings ('1', '0', 'true', 'off' ...). +function parseTrustProxy(v) { + if (v === undefined || v === null || v === '') return 'auto'; + if (v === true || v === false) return v; + if (typeof v === 'number') return v !== 0; + const s = String(v).trim().toLowerCase(); + if (s === 'auto') return 'auto'; + if (['1', 'true', 'yes', 'on'].includes(s)) return true; + if (['0', 'false', 'no', 'off'].includes(s)) return false; + throw new Error('invalid trustProxy value: ' + JSON.stringify(v) + " (use 'auto', '1' or '0')"); +} + +function peerIp(req) { + return normalizeIp(req.socket && req.socket.remoteAddress) || 'unknown'; +} + +// TRUSTED_PROXIES: extra proxy addresses believed under TRUST_PROXY=auto, on top of the private ranges. The built-in +// "private" list misses a proxy that reaches the game over a global IPv6 address, Tailscale / CGNAT (100.64.0.0/10) or +// any other routable address. Accepts an array or a comma separated string of IPs and CIDRs, IPv4 or IPv6 +// ("100.64.0.0/10, 2001:db8::6, 2001:db8:1::/48"). Returns null for an empty list, throws on a malformed entry (a +// typo must stop the start-up, not silently leave the proxy untrusted). The result has .has(ip) and .list. +function parseTrustedProxies(v) { + const items = Array.isArray(v) ? v : String(v === undefined || v === null ? '' : v).split(','); + const list = items.map((s) => String(s).trim()).filter(Boolean); + if (!list.length) return null; + const bl = new net.BlockList(); + for (const item of list) { + const slash = item.indexOf('/'); + const addr = normalizeIp(slash < 0 ? item : item.slice(0, slash)); + const type = net.isIPv4(addr) ? 'ipv4' : net.isIPv6(addr) ? 'ipv6' : null; + const max = type === 'ipv4' ? 32 : 128; + const prefixText = slash < 0 ? null : item.slice(slash + 1); + const prefix = prefixText === null ? max : (/^\d{1,3}$/.test(prefixText) ? Number(prefixText) : NaN); + if (!type || !(prefix >= 0 && prefix <= max) || + (item.startsWith('::ffff:') && slash >= 0)) { // a v4-mapped prefix would need its own arithmetic: write the IPv4 form + throw new Error('invalid TRUSTED_PROXIES entry ' + JSON.stringify(item) + ' (use an IP or CIDR such as 100.64.0.0/10 or 2001:db8::6)'); + } + if (prefixText === null) bl.addAddress(addr, type); else bl.addSubnet(addr, prefix, type); + } + return { + list, + has(ip) { + const a = normalizeIp(ip); + return net.isIPv4(a) ? bl.check(a, 'ipv4') : net.isIPv6(a) ? bl.check(a, 'ipv6') : false; + }, + }; +} + +// Does this request come from a proxy whose X-Forwarded-* headers we believe? `trusted` = parseTrustedProxies() result. +function isTrustedPeer(req, trustProxy, trusted) { + if (trustProxy === true) return true; + if (trustProxy === false) return false; + const ip = peerIp(req); + return isPrivateIp(ip) || !!(trusted && trusted.has(ip)); +} + +// One entry of a forwarding header ("203.0.113.9", "[2001:db8::5]:443", "1.2.3.4:5555") -> bare IP or null. +function parseForwardedEntry(raw) { + let a = String(raw).trim(); + if (!a) return null; + if (a[0] === '[') { const e = a.indexOf(']'); if (e < 0) return null; a = a.slice(1, e); } + else if (/^\d+\.\d+\.\d+\.\d+:\d+$/.test(a)) a = a.slice(0, a.lastIndexOf(':')); + a = normalizeIp(a); + return net.isIP(a) ? a : null; +} + +// First address of a header value like "203.0.113.9, 10.0.0.2" (used for X-Real-IP, which holds one address). +function firstForwardedIp(value) { + return typeof value === 'string' ? parseForwardedEntry(value.split(',')[0]) : null; +} + +// The client address in an X-Forwarded-For built by proxies that APPEND (nginx $proxy_add_x_forwarded_for, which is +// what nginx Proxy Manager does): everything left of the proxy's own entry is whatever the client chose to send, so +// the first entry is forgeable (it lets a client dodge the per-IP cap or use up somebody else's). Walk from the +// right instead, skip the private addresses of our own proxy hops and take the first public one. A chain that is +// private all the way (LAN clients) yields its rightmost entry, i.e. what the nearest proxy saw; junk -> null. +function forwardedClientIp(value) { + if (typeof value !== 'string') return null; + const parts = value.split(','); + let nearest = null; + for (let i = parts.length - 1; i >= 0; i--) { + const ip = parseForwardedEntry(parts[i]); + if (!ip) return nearest; + if (!isPrivateIp(ip)) return ip; + if (!nearest) nearest = ip; + } + return nearest; +} + +// The address used for logging and the per-IP socket cap. +function clientIp(req, trustProxy, trusted) { + const peer = peerIp(req); + if (!isTrustedPeer(req, trustProxy, trusted)) return peer; + return forwardedClientIp(req.headers['x-forwarded-for']) || + firstForwardedIp(req.headers['x-real-ip']) || peer; +} + +// ---------------------------------------------------------------- Origin check +// Scheme-less, lower-case host name and port of a bare host ("Game.Example.com:443"), a Host header or a full origin +// ("https://x.example"): { name, port }, with port '' for none or for the default ports 80 / 443. null if unusable. +function hostParts(s) { + if (typeof s !== 'string') return null; + let v = s.trim(); + if (!v) return null; + if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) { + if (!/^[a-z0-9._:\[\]-]+$/i.test(v)) return null; // a bare host[:port], nothing else + v = 'http://' + v; + } + let u; + try { u = new URL(v); } catch (e) { return null; } + if (!u.hostname) return null; + const port = u.port; // '' for the scheme's own default + return { name: u.hostname.toLowerCase(), port: port && port !== '80' && port !== '443' ? port : '' }; // IPv6 keeps its brackets +} + +// "host[:port]" form of hostParts(). +function normalizeHost(s) { + const p = hostParts(s); + return p ? (p.port ? p.name + ':' + p.port : p.name) : null; +} + +// Returns true when a WebSocket upgrade with this Origin may proceed. +// no Origin header -> true (non-browser clients) +// Origin host == Host -> true +// Origin host == X-Forwarded-Host (first) -> true, only when the peer is a trusted proxy +// Origin host name == Host name, Host without a port -> true, only when the peer is a trusted proxy (see below) +// Origin host in allowedOrigins -> true +// opts: { trustProxy, trustedProxies (parseTrustedProxies() result), allowedOrigins }. +function originAllowed(req, opts) { + const origin = req.headers.origin; + if (origin === undefined) return true; + const o = (typeof origin === 'string' && origin.toLowerCase() !== 'null' && /^[a-z][a-z0-9+.-]*:\/\//i.test(origin)) + ? hostParts(origin) : null; + if (!o) return false; + const h = hostParts(req.headers.host); + if (h && o.name === h.name && o.port === h.port) return true; + if (isTrustedPeer(req, opts.trustProxy, opts.trustedProxies)) { + const xfh = req.headers['x-forwarded-host']; + if (typeof xfh === 'string' && normalizeHost(xfh.split(',')[0]) === normalizeHost(origin)) return true; + // Published on a port other than 80/443 (https://game.example.com:8443) behind nginx / nginx Proxy Manager: their + // "proxy_set_header Host $host" drops the port, so Host is "game.example.com" while the browser's Origin keeps + // ":8443", and neither the X-Forwarded-Host nor an ALLOWED_ORIGINS entry written without the port helps. A browser that + // talks to this server directly on its port (8080 by default, never 80/443 unless you chose that) puts the port in + // Host, so a Host WITHOUT one from a trusted proxy is what a stripped port looks like: accept the same host name on + // any port. Another name still fails. + if (h && !h.port && o.name === h.name) return true; + } + const on = normalizeHost(origin); + for (const a of opts.allowedOrigins || []) if (on === normalizeHost(a)) return true; + return false; +} + +// ---------------------------------------------------------------- token bucket +class TokenBucket { + constructor(ratePerSec, burst) { + this.rate = ratePerSec; this.burst = burst; + this.tokens = burst; this.last = performance.now(); + } + // true when the event is allowed. `now` (ms) defaults to a monotonic clock: with Date.now() a wall-clock step + // backwards (NTP, a VM resume) would stop the refill for as long as the step is large and get sockets closed 4429. + take(now) { + now = now === undefined ? performance.now() : now; + const dt = now - this.last; + if (dt > 0) { this.tokens = Math.min(this.burst, this.tokens + dt * this.rate / 1000); this.last = now; } + if (this.tokens < 1) return false; + this.tokens -= 1; + return true; + } +} + +// ---------------------------------------------------------------- listen +const V6_FALLBACK_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EPROTONOSUPPORT', 'ENOTSUP', 'EINVAL', 'ENOPROTOOPT', 'EPFNOSUPPORT']); + +function listenOnce(server, opts) { + return new Promise((resolve, reject) => { + const onError = (err) => { server.removeListener('listening', onListening); reject(err); }; + const onListening = () => { server.removeListener('error', onError); resolve(); }; + server.once('error', onError); + server.once('listening', onListening); + try { server.listen(opts); } catch (err) { onError(err); } + }); +} + +// Binds `host`. The default '::' is bound dual-stack (ipv6Only:false: one socket for IPv4 and IPv6); +// if IPv6 is unavailable (EAFNOSUPPORT, EADDRNOTAVAIL, ...) it falls back to 0.0.0.0. Any other host is +// used as given, and any other failure (EADDRINUSE, EACCES) is rejected, never papered over. +// Resolves to the host that ended up bound. +async function listenDual(server, port, host, log) { + if (host !== '::') { await listenOnce(server, { port, host }); return host; } + try { + await listenOnce(server, { port, host: '::', ipv6Only: false }); + return '::'; + } catch (err) { + if (!err || !V6_FALLBACK_CODES.has(err.code)) throw err; + if (log) log('IPv6 is not available (' + err.code + '); falling back to 0.0.0.0 (IPv4 only)'); + await listenOnce(server, { port, host: '0.0.0.0' }); + return '0.0.0.0'; + } +} + +// ---------------------------------------------------------------- start-up banner +function fmtUrl(host, port) { + return 'http://' + (host.includes(':') ? '[' + host + ']' : host) + ':' + port + '/'; +} + +// os.networkInterfaces() throws in some sandboxes (seccomp / RestrictAddressFamilies without AF_NETLINK, certain +// containers). The banner is cosmetic, so that must never stop a server that is already listening. +function interfaces() { + try { return os.networkInterfaces(); } catch (e) { return {}; } +} + +// URLs worth printing for a server bound to `bound` on `port`. +function listUrls(bound, port, ifaces) { + const out = ['http://localhost:' + port + '/']; + if (bound !== '::' && bound !== '0.0.0.0') { + if (bound !== '127.0.0.1' && bound !== '::1') out.push(fmtUrl(bound, port)); + return out; + } + ifaces = ifaces || interfaces(); + for (const name of Object.keys(ifaces)) { + for (const a of ifaces[name] || []) { + if (a.internal) continue; + const v4 = a.family === 'IPv4' || a.family === 4; + if (v4) out.push(fmtUrl(a.address, port)); + else if (bound === '::' && !/^fe80:/i.test(a.address)) out.push(fmtUrl(a.address.split('%')[0], port)); + } + } + return out; +} + +module.exports = { + normalizeIp, isPrivateIp, parseTrustProxy, parseTrustedProxies, peerIp, isTrustedPeer, firstForwardedIp, forwardedClientIp, clientIp, + hostParts, normalizeHost, originAllowed, TokenBucket, listenDual, listUrls, fmtUrl, +}; diff --git a/server/queries.js b/server/queries.js new file mode 100644 index 0000000..4c07c45 --- /dev/null +++ b/server/queries.js @@ -0,0 +1,116 @@ +'use strict'; +/* + * Read models. Every read first catches the event queue up to now, so what a player sees is never stale by an + * overdue event. Reads never write (settling is only done by commands and events). + */ +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); +const { GameError } = require('./errors'); +const { loadWorld, townFromRow, pendingBuilds } = require('./state'); + +function createQueries({ db, clock, scheduler }) { + const fresh = () => { scheduler.runDue(); return clock.now(); }; + + function worldView(w) { + return { id: w.id, name: w.name, speed: w.speed, mapRadius: w.map_radius, seed: w.seed, startAt: w.start_at, endAt: w.end_at, status: w.status, preset: w.preset }; + } + + function me(userId) { + const now = fresh(); + const user = db.get('SELECT id, username, created_at FROM users WHERE id = ?', userId); + if (!user) throw new GameError('unauthorized'); + const operators = db.all('SELECT * FROM operators WHERE user_id = ? ORDER BY id', userId).map((o) => { + 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 { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators }; + } + + function planView(p) { + return { ok: p.ok, code: p.ok ? null : p.code, toLevel: p.toLevel, cost: p.cost, durationMs: p.durationMs, missing: p.missing || [] }; + } + + // Full POP state for its owner. + function town(userId, townId) { + const now = fresh(); + const row = db.get('SELECT t.* FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?', townId, userId); + if (!row) throw new GameError('not_found', { what: 'town' }); + const world = loadWorld(db, row.world_id); + const t = townFromRow(db, row, world); + const pending = pendingBuilds(db, t.id); + const cur = R.resourcesAt(t, now); + const rates = cur.rates; + const resources = {}; + for (const r of D.RESOURCES) resources[r] = { amount: cur.amounts[r], rate: rates[r], cap: cur.caps[r] }; + const power = { out: rates.powerOut, draw: rates.powerDraw, net: rates.powerNet, buffer: cur.amounts.battery, bufferCap: cur.caps.battery, bufferRate: rates.powerNet * world.speed, online: R.unitsOnline(t, now) }; + + const buildings = []; + const entry = (key, type, level) => { + const plan = R.buildPlan(t, key, now, pending); + const def = D.BUILDINGS[type]; + buildings.push({ key, type, kind: def.kind, level, maxLevel: def.maxLevel, next: planView(plan) }); + }; + for (let i = 1; i <= D.FIELD_SLOTS; i++) { const k = 'f' + i; if (t.buildings[k]) entry(k, t.buildings[k].type, t.buildings[k].level); } + for (const type of Object.keys(D.BUILDINGS)) { + const def = D.BUILDINGS[type]; + if (def.kind !== 'infra') continue; + if (def.special && !t.buildings[type]) continue; + entry(type, type, t.buildings[type] ? t.buildings[type].level : 0); + } + const queue = pending.map((p) => ({ id: p.id, key: p.key, type: p.type, toLevel: p.toLevel, startedAt: p.startedAt, dueAt: p.dueAt })); + const loyalty = R.loyaltyAt(t.loyalty, t.loyaltyAt, now, world.speed); + return { + serverTime: now, + town: { + id: t.id, name: t.name, x: t.x, y: t.y, isCapital: t.isCapital, ownerId: t.ownerId, worldId: t.worldId, + loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t), + resources, power, buildings, queue, queueSlots: R.queueSlots(t), + bonus: t.bonus, + }, + }; + } + + // Map viewport: everything non-trivial inside the square (x±r, y±r). Land tiles are implied (not listed). + function map(userId, { worldId, x, y, r }) { + const now = fresh(); + let world; + if (worldId !== undefined) world = loadWorld(db, worldId); + else { + const op = db.get('SELECT world_id FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId); + world = op ? loadWorld(db, op.world_id) : null; + } + if (!world) throw new GameError('not_found', { what: 'world' }); + if (!db.get('SELECT 1 AS x FROM operators WHERE user_id = ? AND world_id = ?', userId, world.id)) throw new GameError('not_found', { what: 'world' }); + const rad = world.map_radius; + r = Math.min(r, 40); + const x0 = Math.max(-rad, x - r), x1 = Math.min(rad, x + r), y0 = Math.max(-rad, y - r), y1 = Math.min(rad, y + r); + const specials = []; + for (let yy = y0; yy <= y1; yy++) { + for (let xx = x0; xx <= x1; xx++) { + const t = R.tileAt(world.seed, rad, xx, yy); + 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`, + 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 }, + })); + return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns }; + } + + function notifications(userId, { after, limit }) { + const now = fresh(); + const rows = db.all('SELECT id, type, payload, created_at, read_at, world_id FROM notifications WHERE user_id = ? AND id > ? ORDER BY id LIMIT ?', userId, after || 0, (limit || 50) + 1); + const more = rows.length > (limit || 50); + const items = rows.slice(0, limit || 50).map((n) => ({ id: n.id, type: n.type, worldId: n.world_id, payload: JSON.parse(n.payload), createdAt: n.created_at, readAt: n.read_at })); + return { serverTime: now, items, next: more ? items[items.length - 1].id : null }; + } + + return { me, town, map, notifications, worldView }; +} + +module.exports = { createQueries }; diff --git a/server/routes/auth.js b/server/routes/auth.js new file mode 100644 index 0000000..3598a13 --- /dev/null +++ b/server/routes/auth.js @@ -0,0 +1,61 @@ +'use strict'; +const { GameError } = require('../errors'); +const { reply } = require('../http'); +const { sha256, newToken, hashPassword, verifyPassword } = require('../auth'); + +function register(router, { db, clock, commands, queries, auth, opts }) { + const creds = { + username: { type: 'string', minLength: 3, maxLength: 20, pattern: '^[A-Za-z0-9_-]+$' }, + password: { type: 'string', minLength: 8, maxLength: 128 }, + device: { type: 'string', maxLength: 40 }, + }; + + router.post('/auth/signup', { + summary: 'Create an account, join the world and get a bearer token', tag: 'auth', auth: false, limit: 'auth', + body: { type: 'object', required: ['username', 'password'], properties: Object.assign({ invite: { type: 'string', maxLength: 64 }, worldId: { type: 'integer', minimum: 1 } }, creds) }, + response: { $ref: 'AuthResult' }, status: 201, errors: ['validation_failed', 'username_taken', 'signup_closed', 'world_full', 'rate_limited'], + }, async ({ body }) => { + if (opts.signupCode && body.invite !== opts.signupCode) throw new GameError('signup_closed'); + const passHash = await hashPassword(body.password); + const token = newToken(); + const r = commands.run('signup', { username: body.username, passHash, tokenHash: sha256(token), device: body.device, worldId: body.worldId }); + const me = queries.me(r.userId); + return reply(201, { token, tokenId: r.tokenId, user: { id: r.userId, username: body.username }, operators: me.operators }); + }); + + router.post('/auth/login', { + summary: 'Log in on a device and get a bearer token', tag: 'auth', auth: false, limit: 'auth', + body: { type: 'object', required: ['username', 'password'], properties: creds }, + response: { $ref: 'AuthResult' }, errors: ['validation_failed', 'invalid_credentials', 'forbidden', 'rate_limited'], + }, async ({ body }) => { + const u = db.get('SELECT id, username, pass_hash, banned FROM users WHERE username = ?', body.username); + const ok = await verifyPassword(body.password, u && u.pass_hash); + if (!u || !ok) throw new GameError('invalid_credentials'); + if (u.banned) throw new GameError('forbidden'); + const { token, tokenId } = auth.issueToken(u.id, body.device, clock.now()); + return { token, tokenId, user: { id: u.id, username: u.username }, operators: queries.me(u.id).operators }; + }); + + router.post('/auth/logout', { summary: 'Revoke the token used for this request', tag: 'auth', response: { $ref: 'Ok' }, errors: ['unauthorized'] }, + ({ user, tokenId }) => { + db.run('UPDATE tokens SET revoked_at = ? WHERE id = ? AND user_id = ?', clock.now(), tokenId, user.id); + return {}; + }); + + router.get('/auth/tokens', { + summary: 'List this account\'s active device tokens', tag: 'auth', + response: { type: 'object', required: ['serverTime', 'tokens'], properties: { serverTime: { type: 'integer' }, tokens: { type: 'array', items: { $ref: 'Token' } } } }, errors: ['unauthorized'], + }, ({ user, tokenId }) => ({ + tokens: db.all('SELECT id, device, created_at, last_used_at FROM tokens WHERE user_id = ? AND revoked_at IS NULL ORDER BY id', user.id) + .map((t) => ({ id: t.id, device: t.device, createdAt: t.created_at, lastUsedAt: t.last_used_at, current: t.id === tokenId })), + })); + + router.del('/auth/tokens/:tokenId', { summary: 'Revoke one of this account\'s tokens', tag: 'auth', response: { $ref: 'Ok' }, errors: ['unauthorized', 'not_found'] }, + ({ user, params }) => { + const r = db.run('UPDATE tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL', clock.now(), params.tokenId, user.id); + if (!r.changes) throw new GameError('not_found', { what: 'token' }); + return {}; + }); +} + +module.exports = { register }; diff --git a/server/routes/index.js b/server/routes/index.js new file mode 100644 index 0000000..bbf5683 --- /dev/null +++ b/server/routes/index.js @@ -0,0 +1,9 @@ +'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')]; + +function register(router, services) { + for (const f of files) f.register(router, services); +} + +module.exports = { register }; diff --git a/server/routes/map.js b/server/routes/map.js new file mode 100644 index 0000000..793420c --- /dev/null +++ b/server/routes/map.js @@ -0,0 +1,9 @@ +'use strict'; +function register(router, { queries }) { + router.get('/map', { + summary: 'Map viewport: rural areas, incumbent sites and POPs within (x±r, y±r); land tiles are implied', tag: 'map', + query: { type: 'object', required: ['x', 'y', 'r'], properties: { x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, r: { type: 'integer', minimum: 1, maximum: 40 }, worldId: { type: 'integer', minimum: 1 } } }, + response: { $ref: 'MapResponse' }, errors: ['unauthorized', 'validation_failed', 'not_found'], + }, ({ user, query }) => queries.map(user.id, { worldId: query.worldId, x: query.x, y: query.y, r: query.r })); +} +module.exports = { register }; diff --git a/server/routes/me.js b/server/routes/me.js new file mode 100644 index 0000000..e3596a0 --- /dev/null +++ b/server/routes/me.js @@ -0,0 +1,12 @@ +'use strict'; +function register(router, { queries }) { + router.get('/me', { summary: 'The current user, their operators and POPs', tag: 'me', response: { $ref: 'Me' }, errors: ['unauthorized'] }, + ({ user }) => queries.me(user.id)); + + router.get('/notifications', { + summary: 'Notifications for this user (cursor: after = last seen id)', tag: 'me', + query: { type: 'object', properties: { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } } }, + response: { $ref: 'NotificationList' }, errors: ['unauthorized', 'validation_failed'], + }, ({ user, query }) => queries.notifications(user.id, query)); +} +module.exports = { register }; diff --git a/server/routes/schemas.js b/server/routes/schemas.js new file mode 100644 index 0000000..c600090 --- /dev/null +++ b/server/routes/schemas.js @@ -0,0 +1,43 @@ +'use strict'; +/* Shared response schemas (JSON-schema subset), referenced from route meta as { $ref: 'Name' } and emitted into + * openapi.json components. Responses are documentation (and checked by test/api-contract.test.js), not enforced at runtime. */ +const int = { type: 'integer' }; +const num = { type: 'number' }; +const str = { type: 'string' }; +const bool = { type: 'boolean' }; +const obj = (properties, required) => ({ type: 'object', properties, required: required || Object.keys(properties), additionalProperties: true }); +const arr = (items) => ({ type: 'array', items }); + +const Cost = obj({ fiber: int, hardware: int, capital: int }); + +const schemas = { + Cost, + 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' }) }), + 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 }), + BuildPlan: obj({ ok: bool, code: { type: ['string', 'null'] }, toLevel: int, cost: { $ref: 'Cost' }, durationMs: int, missing: arr(obj({ type: str, level: int, have: int })) }, ['ok', 'code', 'toLevel']), + BuildingView: obj({ key: str, type: str, kind: str, level: int, maxLevel: int, next: { $ref: 'BuildPlan' } }), + QueueEntry: obj({ id: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int }), + ResourceView: obj({ amount: num, rate: num, cap: num }), + Town: obj({ + id: int, name: str, x: int, y: int, isCapital: bool, ownerId: int, worldId: int, loyalty: num, footprint: num, footprintPerDay: num, + resources: obj({ fiber: { $ref: 'ResourceView' }, hardware: { $ref: 'ResourceView' }, capital: { $ref: 'ResourceView' } }), + power: obj({ out: num, draw: num, net: num, buffer: num, bufferCap: num, bufferRate: num, online: bool }), + buildings: arr({ $ref: 'BuildingView' }), queue: arr({ $ref: 'QueueEntry' }), queueSlots: int, + 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 }) }), + 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'] } }), + Ok: obj({ serverTime: int }), +}; + +module.exports = { schemas, int, num, str, bool, obj, arr }; diff --git a/server/routes/towns.js b/server/routes/towns.js new file mode 100644 index 0000000..895bec1 --- /dev/null +++ b/server/routes/towns.js @@ -0,0 +1,27 @@ +'use strict'; +const { reply } = require('../http'); + +function register(router, { queries, commands }) { + const errs = ['unauthorized', 'not_found']; + + router.get('/towns/:id', { summary: 'Full state of one of your POPs: resources, power, buildings, build queue', tag: 'towns', response: { $ref: 'TownResponse' }, errors: errs }, + ({ user, params }) => queries.town(user.id, params.id)); + + router.post('/towns/:id/build', { + summary: 'Build or upgrade a building (fields f1..f18 or an infrastructure building type) by one level', tag: 'towns', + body: { type: 'object', required: ['key'], properties: { key: { type: 'string', maxLength: 32, pattern: '^[a-z0-9_]+$' } } }, + response: { $ref: 'BuildResult' }, status: 201, + errors: errs.concat(['validation_failed', 'unknown_building', 'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources']), + }, ({ user, params, body }) => { + return reply(201, commands.run('build', { userId: user.id, townId: params.id, key: body.key })); + }); + + router.del('/towns/:id/queue/:eventId', { summary: 'Cancel a running build and get 80% of its cost back', tag: 'towns', response: { $ref: 'Ok' }, errors: errs }, + ({ user, params }) => { commands.run('cancelBuild', { userId: user.id, townId: params.id, eventId: params.eventId }); return {}; }); + + router.post('/towns/:id/rename', { + summary: 'Rename a POP', tag: 'towns', body: { type: 'object', required: ['name'], properties: { name: { type: 'string', minLength: 2, maxLength: 40 } } }, + response: { type: 'object', required: ['serverTime', 'name'], properties: { serverTime: { type: 'integer' }, name: { type: 'string' } } }, errors: errs.concat(['validation_failed']), + }, ({ user, params, body }) => commands.run('renameTown', { userId: user.id, townId: params.id, name: body.name })); +} +module.exports = { register }; diff --git a/server/scheduler.js b/server/scheduler.js new file mode 100644 index 0000000..873833a --- /dev/null +++ b/server/scheduler.js @@ -0,0 +1,95 @@ +'use strict'; +/* + * Persistent event queue. There is no tick loop: one timer points at the next due event, and after a restart every + * overdue event is caught up in order before traffic is accepted. + * + * Rules (CLAUDE.md "Time model"): + * - events are processed strictly in (due_at, id) order + * - each event runs in ONE transaction: handler + mark done. A handler that throws rolls back and the event is + * marked failed (never retried in a loop, never blocks the queue) + * - handlers must be idempotent; they receive the event's own due_at as the time to settle towns to + * - before any command or read touches a town, runDue() processes everything due up to `now` + */ +const MAX_TIMER_MS = 30 * 1000; // re-check at least this often (setTimeout cannot do more than ~24 days anyway) + +class Scheduler { + // handlers: { [type]: (ctx, event) => void }; ctx = { db, clock, now, enqueue, notify, log } + constructor({ db, clock, handlers, log, autoArm }) { + this.db = db; this.clock = clock; this.handlers = handlers || {}; this.log = log || (() => {}); + this.autoArm = autoArm !== false; + this.timer = null; this.running = false; this.closed = false; + this.onEvent = null; // optional hook: (event) => void after each processed event (push, tests) + } + + register(type, fn) { this.handlers[type] = fn; } + + // Insert an event. Call inside a transaction together with the state change it belongs to. + enqueue({ worldId, dueAt, type, townId, payload }) { + const r = this.db.run('INSERT INTO events (world_id, due_at, type, town_id, payload, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)', + worldId, Math.round(dueAt), type, townId === undefined ? null : townId, JSON.stringify(payload || {}), 'pending', this.clock.now()); + return Number(r.lastInsertRowid); + } + + notify(userId, worldId, type, payload) { + this.db.run('INSERT INTO notifications (user_id, world_id, type, payload, created_at) VALUES (?, ?, ?, ?, ?)', + userId, worldId === undefined ? null : worldId, type, JSON.stringify(payload || {}), this.clock.now()); + } + + next() { return this.db.get("SELECT id, due_at FROM events WHERE status = 'pending' ORDER BY due_at, id LIMIT 1"); } + + // Process every pending event with due_at <= now, in order, including follow-ups that are also already due. + // Returns the number processed. Reentrancy-safe: a handler cannot start a nested run. + runDue(now) { + if (this.running) return 0; + this.running = true; + let n = 0; + try { + now = now === undefined ? this.clock.now() : now; + for (;;) { + const ev = this.db.get("SELECT * FROM events WHERE status = 'pending' AND due_at <= ? ORDER BY due_at, id LIMIT 1", now); + if (!ev) break; + this.process(ev); + n++; + } + } finally { this.running = false; } + return n; + } + + process(ev) { + const handler = this.handlers[ev.type]; + const event = { id: ev.id, worldId: ev.world_id, dueAt: ev.due_at, type: ev.type, townId: ev.town_id, payload: JSON.parse(ev.payload) }; + try { + this.db.tx(() => { + if (!handler) throw new Error('no handler for event type ' + ev.type); + handler({ db: this.db, clock: this.clock, now: ev.due_at, enqueue: (e) => this.enqueue(e), notify: (u, w, t, p) => this.notify(u, w, t, p), log: this.log, scheduler: this }, event); + this.db.run("UPDATE events SET status = 'done', done_at = ? WHERE id = ?", this.clock.now(), ev.id); + }); + } catch (err) { + this.log('event ' + ev.id + ' (' + ev.type + ') failed: ' + (err && err.stack || err)); + this.db.run("UPDATE events SET status = 'failed', done_at = ?, error = ? WHERE id = ?", this.clock.now(), String(err && err.message || err).slice(0, 500), ev.id); + return; + } + if (this.onEvent) { try { this.onEvent(event); } catch (e) { this.log('onEvent hook failed: ' + e.message); } } + } + + // After a restart: process everything overdue, in order, before accepting traffic. + catchUp() { return this.runDue(); } + + // Point the single timer at the next due event (or re-check soon). Safe to call after every mutation. + arm() { + if (!this.autoArm || this.closed) return; + if (this.timer) { clearTimeout(this.timer); this.timer = null; } + const nx = this.next(); + const wait = nx ? Math.min(MAX_TIMER_MS, Math.max(0, nx.due_at - this.clock.now())) : MAX_TIMER_MS; + this.timer = setTimeout(() => { + this.timer = null; + try { this.runDue(); } catch (err) { this.log('scheduler run failed: ' + (err && err.stack || err)); } + this.arm(); + }, wait + 5); + if (this.timer.unref) this.timer.unref(); + } + + stop() { this.closed = true; if (this.timer) clearTimeout(this.timer); this.timer = null; } +} + +module.exports = { Scheduler }; diff --git a/server/state.js b/server/state.js new file mode 100644 index 0000000..e2a0182 --- /dev/null +++ b/server/state.js @@ -0,0 +1,78 @@ +'use strict'; +/* + * Loading towns from the database into the shape rules.js works on, and settling them (storing the current value at a + * new time before something that changes a rate is applied). Shared by commands, events and queries. + */ +const R = require('../public/js/rules.js'); +const D = require('../public/js/data.js'); + +// Cached world rows: they never change while the server runs (config is read at boot and on admin edits). +function loadWorld(db, id) { + const w = db.get('SELECT * FROM worlds WHERE id = ?', id); + return w ? Object.assign(w, { config: JSON.parse(w.config || '{}') }) : null; +} + +// rules.js town shape from a towns row. `unitDraw` comes from the military module when it exists. +function townFromRow(db, row, world) { + const buildings = {}; + for (const b of db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', row.id)) buildings[b.key] = { type: b.type, level: b.level }; + world = world || loadWorld(db, row.world_id); + return { + id: row.id, worldId: row.world_id, ownerId: row.owner_id, name: row.name, x: row.x, y: row.y, + isCapital: !!row.is_capital, speed: world.speed, + updatedAt: row.res_at, footprint: row.footprint, + res: { fiber: row.fiber, hardware: row.hardware, capital: row.capital, battery: row.battery }, + loyalty: row.loyalty, loyaltyAt: row.loyalty_at, + buildings, + unitDraw: unitDraw(db, row.id), + bonus: R.ruralBonus(world.seed, world.map_radius, row.x, row.y), + }; +} + +// Total power draw of units stationed in a town. Military stage fills this in (table town_units). +function unitDraw(db, townId) { + if (!hasTable(db, 'town_units')) return 0; + 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; + return draw; +} + +const tableCache = new Map(); +function hasTable(db, name) { + if (!tableCache.has(db)) tableCache.set(db, new Map()); + const m = tableCache.get(db); + if (!m.get(name)) m.set(name, !!db.get("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?", name)); + return m.get(name); +} + +function loadTown(db, id) { + const row = db.get('SELECT * FROM towns WHERE id = ?', id); + return row ? townFromRow(db, row) : null; +} + +// Bring the stored values up to `at`. Call before any change to buildings or units of this town. Mutates `town`. +function settle(db, town, at) { + if (at < town.updatedAt) at = town.updatedAt; // never go backwards + const cur = R.resourcesAt(town, at).amounts; + const fp = R.footprintAt(town, at); + const loy = R.loyaltyAt(town.loyalty, town.loyaltyAt, at, town.speed); + db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ?, res_at = ?, loyalty = ?, loyalty_at = ? WHERE id = ?', + cur.fiber, cur.hardware, cur.capital, cur.battery, fp, at, loy, at, town.id); + town.res = { fiber: cur.fiber, hardware: cur.hardware, capital: cur.capital, battery: cur.battery }; + town.footprint = fp; town.updatedAt = at; town.loyalty = loy; town.loyaltyAt = at; + return town; +} + +// Subtract a cost from a settled town (persists). Caller has already checked affordability. +function spend(db, town, cost) { + for (const r of D.RESOURCES) town.res[r] -= cost[r] || 0; + db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id); +} + +function pendingBuilds(db, townId) { + return db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'buildDone' AND status = 'pending' ORDER BY due_at, id", townId) + .map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload))); +} + +module.exports = { loadWorld, loadTown, townFromRow, settle, spend, pendingBuilds, hasTable }; diff --git a/server/static.js b/server/static.js new file mode 100644 index 0000000..1fe77ee --- /dev/null +++ b/server/static.js @@ -0,0 +1,181 @@ +'use strict'; +/* + * Minimal, safe static file server for public/. + * - GET / HEAD only (405 otherwise), never serves anything outside the root (also not via symlinks) + * - rejects "..", %2e%2e, %2f, %5c, backslashes, NUL and control characters (400), dotfiles (404) + * - ETag / If-None-Match / Last-Modified (304) with Cache-Control: no-cache + * - single-range requests (206): iOS Safari will not play