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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:07:42 +02:00
parent 9fa76d53a8
commit b56b13880e
39 changed files with 4450 additions and 0 deletions

106
public/js/data.js Normal file
View file

@ -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 };
}));

300
public/js/rules.js Normal file
View file

@ -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,
};
}));