Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy

Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:32:36 +02:00
parent b56b13880e
commit 249818a7aa
111 changed files with 17472 additions and 13 deletions

180
server/alliances.js Normal file
View file

@ -0,0 +1,180 @@
'use strict';
/*
* Alliance data helpers shared by commands, events, queries and (later) the military stage.
*
* Other modules use the lookups at the bottom:
* relationBetween(db, allianceA, allianceB) -> 'war' | 'neutral' | 'nap' | 'confed'
* operatorRelation(db, opA, opB) -> 'self' | 'same_alliance' | 'war' | 'neutral' | 'nap' | 'confed'
* atWar(db, opA, opB), confederated(db, opA, opB), pactPartners(db, opA, opB)
*
* Membership is kept in alliance_members (role) and operators.alliance_id (quick lookup). addMember / removeMember
* are the only writers of both.
*/
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { GameError } = require('./errors');
const S = D.SOCIAL;
const HOUR = D.HOUR_MS;
// ------------------------------------------------------------------ operators and membership
// The caller's operator. With worldId: the one in that world; without: their oldest. not_found when there is none.
function operatorOf(db, userId, worldId) {
const row = worldId !== undefined && worldId !== null
? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId)
: db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
if (!row) throw new GameError('not_found', { what: 'operator' });
return row;
}
// Best (highest) completed Peering office level over all POPs of an operator.
function peeringLevel(db, operatorId) {
const r = db.get(`SELECT MAX(b.level) AS lvl FROM buildings b JOIN towns t ON t.id = b.town_id
WHERE t.owner_id = ? AND b.type = 'peering_office'`, operatorId);
return r && r.lvl ? r.lvl : 0;
}
const membership = (db, operatorId) => db.get('SELECT operator_id, alliance_id, role, joined_at FROM alliance_members WHERE operator_id = ?', operatorId) || null;
const getAlliance = (db, id) => db.get('SELECT * FROM alliances WHERE id = ?', id) || null;
const memberCount = (db, allianceId) => db.get('SELECT COUNT(*) AS n FROM alliance_members WHERE alliance_id = ?', allianceId).n;
const leaderOf = (db, allianceId) => db.get("SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND role = 'leader'", allianceId);
// { id, tag, name } or null, for embedding in other views (/me, /map).
function allianceBrief(db, id) {
if (id === null || id === undefined) return null;
const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id);
return a || null;
}
// The cap that applies now: the stored one, raised if the current leader's best Peering office would give more.
// Never lowered (a lost building must not kick anyone). Pure read; `refreshCap` persists a raise.
function effectiveCap(db, alliance) {
const lead = leaderOf(db, alliance.id);
const fromLeader = lead ? R.allianceCap(peeringLevel(db, lead.operator_id)) : 0;
return Math.max(alliance.size_cap, fromLeader);
}
function refreshCap(db, alliance) {
const cap = effectiveCap(db, alliance);
if (cap > alliance.size_cap) { db.run('UPDATE alliances SET size_cap = ? WHERE id = ?', cap, alliance.id); alliance.size_cap = cap; }
return cap;
}
function addMember(db, allianceId, operatorId, role, now) {
db.run('INSERT INTO alliance_members (operator_id, alliance_id, role, joined_at) VALUES (?, ?, ?, ?)', operatorId, allianceId, role, now);
db.run('UPDATE operators SET alliance_id = ? WHERE id = ?', allianceId, operatorId);
// Any other open invites of this operator are moot now.
db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE operator_id = ? AND status = 'pending' AND alliance_id <> ?", now, operatorId, allianceId);
}
function removeMember(db, operatorId) {
db.run('DELETE FROM alliance_members WHERE operator_id = ?', operatorId);
db.run('UPDATE operators SET alliance_id = NULL WHERE id = ?', operatorId);
}
// Authorise an alliance action. Returns { op, alliance, member }. not_found: no such alliance (or the caller has no
// operator in its world); forbidden: not a member, or the role may not do `action`.
function requireRole(db, userId, allianceId, action) {
const alliance = getAlliance(db, allianceId);
if (!alliance) throw new GameError('not_found', { what: 'alliance' });
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id);
if (!op) throw new GameError('not_found', { what: 'alliance' });
const member = membership(db, op.id);
if (!member || member.alliance_id !== alliance.id) throw new GameError('forbidden', { need: 'member' });
if (action && !R.allianceCan(member.role, action)) throw new GameError('forbidden', { need: action, role: member.role });
return { op, alliance, member };
}
// ------------------------------------------------------------------ notifications (rows in `notifications`)
const userOfOperator = (db, operatorId) => { const r = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return r ? r.user_id : null; };
function notifyOperator(ctx, operatorId, type, payload) {
const o = ctx.db.get('SELECT user_id, world_id FROM operators WHERE id = ?', operatorId);
if (o) ctx.scheduler.notify(o.user_id, o.world_id, type, payload);
}
// All members of an alliance, optionally only some roles, optionally skipping one operator.
function notifyAlliance(ctx, allianceId, type, payload, o) {
o = o || {};
const rows = ctx.db.all(`SELECT m.operator_id AS oid, m.role AS role, op.user_id AS uid, op.world_id AS wid
FROM alliance_members m JOIN operators op ON op.id = m.operator_id WHERE m.alliance_id = ?`, allianceId);
for (const r of rows) {
if (o.except && r.oid === o.except) continue;
if (o.roles && o.roles.indexOf(r.role) < 0) continue;
ctx.scheduler.notify(r.uid, r.wid, type, payload);
}
}
// ------------------------------------------------------------------ dissolving
// Remove an alliance and everything hanging off it. Counterparts of non-neutral relations are told it is neutral now.
function dissolve(ctx, allianceId, reason) {
const { db, now } = ctx;
const a = getAlliance(db, allianceId);
if (!a) return;
const brief = { allianceId: a.id, tag: a.tag, name: a.name };
notifyAlliance(ctx, a.id, 'alliance_disbanded', Object.assign({ reason }, brief));
const rels = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id);
for (const r of rels) {
const other = r.a_id === a.id ? r.b_id : r.a_id;
if (r.pending_event) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, r.pending_event);
if (r.state !== 'neutral') notifyAlliance(ctx, other, 'diplomacy_changed', { allianceId: other, otherId: a.id, otherTag: a.tag, from: r.state, to: 'neutral', reason: 'disbanded' });
}
db.run('DELETE FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id);
db.run('DELETE FROM alliance_proposals WHERE from_id = ? OR to_id = ?', a.id, a.id);
db.run('DELETE FROM alliance_invites WHERE alliance_id = ?', a.id);
db.run('DELETE FROM alliance_notes WHERE alliance_id = ?', a.id);
const ids = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id);
for (const m of ids) removeMember(db, m.operator_id);
db.run('DELETE FROM alliances WHERE id = ?', a.id);
}
// ------------------------------------------------------------------ relations
const pairOf = (x, y) => (x < y ? [x, y] : [y, x]);
const getRelation = (db, x, y) => { const [a, b] = pairOf(x, y); return db.get('SELECT * FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b) || null; };
// Set the current state of a pair, clearing any pending change. neutral with nothing pending = no row.
function setRelation(db, worldId, x, y, state, now) {
const [a, b] = pairOf(x, y);
if (state === 'neutral') { db.run('DELETE FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b); return; }
db.run(`INSERT INTO alliance_relations (a_id, b_id, world_id, state, since) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (a_id, b_id) DO UPDATE SET state = excluded.state, since = excluded.since,
pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL`, a, b, worldId, state, now);
}
// Mark every open proposal between two alliances (either direction) as withdrawn: the state moved on under them.
function withdrawProposals(db, x, y, now) {
db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE status = 'pending' AND ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))", now, x, y, y, x);
}
// ------------------------------------------------------------------ lookups for other modules
function relationBetween(db, allianceA, allianceB) {
if (!allianceA || !allianceB || allianceA === allianceB) return 'neutral';
const r = getRelation(db, allianceA, allianceB);
return r ? r.state : 'neutral';
}
function operatorRelation(db, opA, opB) {
if (opA === opB) return 'self';
const rows = db.all('SELECT id, alliance_id FROM operators WHERE id IN (?, ?)', opA, opB);
const a = rows.find((r) => r.id === opA), b = rows.find((r) => r.id === opB);
if (!a || !b || !a.alliance_id || !b.alliance_id) return 'neutral';
if (a.alliance_id === b.alliance_id) return 'same_alliance';
return relationBetween(db, a.alliance_id, b.alliance_id);
}
const atWar = (db, opA, opB) => operatorRelation(db, opA, opB) === 'war';
// Can reinforce each other and see each other's incoming: same alliance or confederation.
const confederated = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'confed' || r === 'same_alliance'; };
// May not attack each other: same alliance, NAP or confederation.
const pactPartners = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'nap' || r === 'confed' || r === 'same_alliance'; };
module.exports = {
S, HOUR, operatorOf, peeringLevel, membership, getAlliance, memberCount, leaderOf, allianceBrief, effectiveCap, refreshCap,
addMember, removeMember, requireRole, userOfOperator, notifyOperator, notifyAlliance, dissolve,
pairOf, getRelation, setRelation, withdrawProposals,
relationBetween, operatorRelation, atWar, confederated, pactPartners,
};

View file

@ -0,0 +1,35 @@
'use strict';
/* POST /alliances. Found an alliance: needs Peering office >= 1 on one of the founder's POPs; the founder becomes
* leader. Size cap = 10 + 2 * best Peering office level at this moment (rules.allianceCap), stored. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { cleanText } = require('../text');
const A = require('../alliances');
const NAME_RE = /^[\p{L}\p{N}][\p{L}\p{N} _.'-]*$/u;
module.exports = function allianceCreate(ctx, { userId, worldId, name, tag }) {
const { db, now } = ctx;
const S = A.S;
const op = A.operatorOf(db, userId, worldId);
if (A.membership(db, op.id)) throw new GameError('already_in_alliance', { allianceId: A.membership(db, op.id).alliance_id });
const lvl = A.peeringLevel(db, op.id);
if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel });
name = cleanText(name);
tag = cleanText(tag);
const errors = [];
const len = [...name].length;
if (len < S.nameLen[0] || len > S.nameLen[1] || !NAME_RE.test(name)) errors.push({ path: 'name', message: 'must be ' + S.nameLen[0] + '-' + S.nameLen[1] + ' letters, digits, spaces or _ . \' -' });
if (!/^[A-Za-z0-9]+$/.test(tag) || tag.length < S.tagLen[0] || tag.length > S.tagLen[1]) errors.push({ path: 'tag', message: 'must be ' + S.tagLen[0] + '-' + S.tagLen[1] + ' letters or digits' });
if (errors.length) throw new GameError('validation_failed', { errors });
if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND name = ?', op.world_id, name)) throw new GameError('alliance_name_taken');
if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND tag = ?', op.world_id, tag)) throw new GameError('alliance_tag_taken');
const cap = R.allianceCap(lvl);
const r = db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)', op.world_id, name, tag, cap, op.id, now);
const id = Number(r.lastInsertRowid);
A.addMember(db, id, op.id, 'leader', now);
return { allianceId: id, name, tag, sizeCap: cap, role: 'leader' };
};

View file

@ -0,0 +1,9 @@
'use strict';
/* POST /alliances/:id/disband. Leader only. Removes members, invites, notes, proposals and relations. */
const A = require('../alliances');
module.exports = function allianceDisband(ctx, { userId, allianceId }) {
const { alliance } = A.requireRole(ctx.db, userId, allianceId, 'disband');
A.dissolve(ctx, alliance.id, 'disbanded');
return { changed: true };
};

View file

@ -0,0 +1,32 @@
'use strict';
/* POST /alliances/:id/invite. Needs the `invite` permission. Target by operator id or name (same world). Idempotent:
* a second invite to the same operator returns the pending one. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceInvite(ctx, { userId, allianceId, operatorId, name }) {
const { db, now } = ctx;
const S = A.S;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'invite');
const target = operatorId !== undefined
? db.get('SELECT * FROM operators WHERE id = ? AND world_id = ?', operatorId, alliance.world_id)
: db.get('SELECT * FROM operators WHERE name = ? COLLATE NOCASE AND world_id = ?', name, alliance.world_id);
if (!target) throw new GameError('not_found', { what: 'operator' });
if (target.id === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you cannot invite yourself' }] });
const m = A.membership(db, target.id);
if (m) throw new GameError('already_in_alliance', { allianceId: m.alliance_id });
db.run("UPDATE alliance_invites SET status = 'expired', answered_at = ? WHERE status = 'pending' AND expires_at <= ?", now, now);
const open = db.get("SELECT id, expires_at FROM alliance_invites WHERE alliance_id = ? AND operator_id = ? AND status = 'pending'", alliance.id, target.id);
if (open) return { inviteId: open.id, operatorId: target.id, expiresAt: open.expires_at, changed: false };
if (A.memberCount(db, alliance.id) >= A.refreshCap(db, alliance)) throw new GameError('alliance_full', { cap: alliance.size_cap });
const pending = db.get("SELECT COUNT(*) AS n FROM alliance_invites WHERE alliance_id = ? AND status = 'pending'", alliance.id).n;
if (pending >= S.maxPendingInvites) throw new GameError('conflict', { what: 'too many pending invites', max: S.maxPendingInvites });
const expiresAt = now + Math.round(S.inviteTtlHours * A.HOUR);
const r = db.run('INSERT INTO alliance_invites (alliance_id, operator_id, invited_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?)', alliance.id, target.id, op.id, now, expiresAt);
const inviteId = Number(r.lastInsertRowid);
A.notifyOperator(ctx, target.id, 'alliance_invite', { inviteId, allianceId: alliance.id, tag: alliance.tag, name: alliance.name, by: op.name, expiresAt });
return { inviteId, operatorId: target.id, expiresAt, changed: true };
};

View file

@ -0,0 +1,41 @@
'use strict';
/* POST /alliance-invites/:id/accept | /decline. Only the invited operator's user. Accepting needs Peering office >= 1,
* no current alliance, and room (cap re-evaluated). Answering an already answered invite the same way is a no-op. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceInviteAnswer(ctx, { userId, inviteId, accept }) {
const { db, now } = ctx;
const S = A.S;
const inv = db.get(`SELECT i.*, o.user_id AS uid, o.name AS oname FROM alliance_invites i JOIN operators o ON o.id = i.operator_id WHERE i.id = ?`, inviteId);
if (!inv || inv.uid !== userId) throw new GameError('not_found', { what: 'invite' });
if (inv.status !== 'pending') {
if ((accept && inv.status === 'accepted') || (!accept && inv.status === 'declined')) return { changed: false, allianceId: inv.alliance_id };
throw new GameError(inv.status === 'expired' ? 'invite_expired' : 'conflict', { what: 'invite is ' + inv.status });
}
if (inv.expires_at <= now) {
// The refusal rolls this transaction back; the invite is simply treated as expired whenever it is looked at.
throw new GameError('invite_expired', { expiresAt: inv.expires_at });
}
const alliance = A.getAlliance(db, inv.alliance_id);
if (!alliance) throw new GameError('not_found', { what: 'alliance' });
if (!accept) {
db.run("UPDATE alliance_invites SET status = 'declined', answered_at = ? WHERE id = ?", now, inv.id);
A.notifyOperator(ctx, inv.invited_by, 'alliance_invite_declined', { inviteId: inv.id, allianceId: alliance.id, by: inv.oname });
return { changed: true, allianceId: alliance.id };
}
const cur = A.membership(db, inv.operator_id);
if (cur) throw new GameError('already_in_alliance', { allianceId: cur.alliance_id });
const lvl = A.peeringLevel(db, inv.operator_id);
if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel });
const cap = A.refreshCap(db, alliance);
if (A.memberCount(db, alliance.id) >= cap) throw new GameError('alliance_full', { cap });
A.addMember(db, alliance.id, inv.operator_id, 'member', now);
db.run("UPDATE alliance_invites SET status = 'accepted', answered_at = ? WHERE id = ?", now, inv.id);
A.notifyAlliance(ctx, alliance.id, 'alliance_member_joined', { allianceId: alliance.id, operatorId: inv.operator_id, name: inv.oname }, { except: inv.operator_id });
return { changed: true, allianceId: alliance.id, role: 'member' };
};

View file

@ -0,0 +1,15 @@
'use strict';
/* DELETE /alliances/:id/invites/:inviteId. Needs `cancelInvite`. Idempotent for an already cancelled invite. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceInviteCancel(ctx, { userId, allianceId, inviteId }) {
const { db, now } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'cancelInvite');
const inv = db.get('SELECT id, status FROM alliance_invites WHERE id = ? AND alliance_id = ?', inviteId, alliance.id);
if (!inv) throw new GameError('not_found', { what: 'invite' });
if (inv.status === 'cancelled') return { changed: false };
if (inv.status !== 'pending') throw new GameError('conflict', { what: 'invite is ' + inv.status });
db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE id = ?", now, inv.id);
return { changed: true };
};

View file

@ -0,0 +1,19 @@
'use strict';
/* POST /alliances/:id/kick. Needs `kick` and the actor must outrank the target. Target not in the alliance: no-op. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceKick(ctx, { userId, allianceId, operatorId }) {
const { db } = ctx;
const { op, alliance, member } = A.requireRole(db, userId, allianceId, 'kick');
if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'use leave to leave an alliance' }] });
const t = A.membership(db, operatorId);
if (!t || t.alliance_id !== alliance.id) return { changed: false };
if (!R.outranks(member.role, t.role)) throw new GameError('forbidden', { need: 'outrank', role: member.role, targetRole: t.role });
const target = db.get('SELECT id, name FROM operators WHERE id = ?', operatorId);
A.removeMember(db, operatorId);
A.notifyOperator(ctx, operatorId, 'alliance_kicked', { allianceId: alliance.id, tag: alliance.tag, name: alliance.name });
A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId, name: target.name, kicked: true });
return { changed: true };
};

View file

@ -0,0 +1,23 @@
'use strict';
/* POST /alliances/:id/leave. The leader cannot leave while others remain (transfer first); a leader who is alone
* dissolves the alliance. Leaving an alliance you are not in is a no-op. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceLeave(ctx, { userId, allianceId }) {
const { db } = ctx;
const alliance = A.getAlliance(db, allianceId);
if (!alliance) throw new GameError('not_found', { what: 'alliance' });
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id);
if (!op) throw new GameError('not_found', { what: 'alliance' });
const m = A.membership(db, op.id);
if (!m || m.alliance_id !== alliance.id) return { changed: false };
if (m.role === 'leader') {
if (A.memberCount(db, alliance.id) > 1) throw new GameError('leader_must_transfer');
A.dissolve(ctx, alliance.id, 'last_member_left');
return { changed: true, disbanded: true };
}
A.removeMember(db, op.id);
A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId: op.id, name: op.name, kicked: false });
return { changed: true, disbanded: false };
};

View file

@ -0,0 +1,41 @@
'use strict';
/* Pinned notes of an alliance. Three commands, one file: allianceNoteAdd / allianceNoteEdit / allianceNoteDelete
* (registered separately in commands/index.js). Needs `editNotes`. */
const { GameError } = require('../errors');
const { cleanText } = require('../text');
const A = require('../alliances');
function text(raw) {
const t = cleanText(raw, { multiline: true });
if (!t || [...t].length > A.S.noteMax) throw new GameError('validation_failed', { errors: [{ path: 'text', message: 'must be 1-' + A.S.noteMax + ' characters of plain text' }] });
return t;
}
const view = (n) => ({ id: n.id, authorId: n.author_id, text: n.text, createdAt: n.created_at, updatedAt: n.updated_at });
function allianceNoteAdd(ctx, { userId, allianceId, text: raw }) {
const { db, now } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'editNotes');
const t = text(raw);
if (db.get('SELECT COUNT(*) AS n FROM alliance_notes WHERE alliance_id = ?', alliance.id).n >= A.S.maxNotes) throw new GameError('notes_full', { max: A.S.maxNotes });
const r = db.run('INSERT INTO alliance_notes (alliance_id, author_id, text, created_at, updated_at) VALUES (?, ?, ?, ?, ?)', alliance.id, op.id, t, now, now);
return { note: view(db.get('SELECT * FROM alliance_notes WHERE id = ?', Number(r.lastInsertRowid))) };
}
function allianceNoteEdit(ctx, { userId, allianceId, noteId, text: raw }) {
const { db, now } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'editNotes');
const t = text(raw);
const r = db.run('UPDATE alliance_notes SET text = ?, updated_at = ? WHERE id = ? AND alliance_id = ?', t, now, noteId, alliance.id);
if (!r.changes) throw new GameError('not_found', { what: 'note' });
return { note: view(db.get('SELECT * FROM alliance_notes WHERE id = ?', noteId)) };
}
function allianceNoteDelete(ctx, { userId, allianceId, noteId }) {
const { db } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'editNotes');
const r = db.run('DELETE FROM alliance_notes WHERE id = ? AND alliance_id = ?', noteId, alliance.id);
return { changed: r.changes > 0 };
}
module.exports = { allianceNoteAdd, allianceNoteEdit, allianceNoteDelete, noteView: view };

View file

@ -0,0 +1,17 @@
'use strict';
/* POST /alliances/:id/role. Needs `setRole` (leader). Roles diplomat | officer | member; use transfer for leadership. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceRole(ctx, { userId, allianceId, operatorId, role }) {
const { db } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'setRole');
if (A.S.roles.indexOf(role) < 0 || role === 'leader') throw new GameError('validation_failed', { errors: [{ path: 'role', message: 'must be diplomat, officer or member' }] });
if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'the leader cannot change their own role; transfer leadership' }] });
const t = A.membership(db, operatorId);
if (!t || t.alliance_id !== alliance.id) throw new GameError('not_found', { what: 'member' });
if (t.role === role) return { changed: false, role };
db.run('UPDATE alliance_members SET role = ? WHERE operator_id = ?', role, operatorId);
A.notifyOperator(ctx, operatorId, 'alliance_role', { allianceId: alliance.id, tag: alliance.tag, from: t.role, role });
return { changed: true, role };
};

View file

@ -0,0 +1,18 @@
'use strict';
/* POST /alliances/:id/transfer. The leader hands leadership to another member and becomes an officer. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceTransfer(ctx, { userId, allianceId, operatorId }) {
const { db } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'transfer');
if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you are already the leader' }] });
const t = A.membership(db, operatorId);
if (!t || t.alliance_id !== alliance.id) throw new GameError('not_found', { what: 'member' });
db.run("UPDATE alliance_members SET role = 'officer' WHERE operator_id = ?", op.id); // before promoting: one leader at a time
db.run("UPDATE alliance_members SET role = 'leader' WHERE operator_id = ?", operatorId);
A.refreshCap(db, alliance);
const target = db.get('SELECT name FROM operators WHERE id = ?', operatorId);
A.notifyAlliance(ctx, alliance.id, 'alliance_leader', { allianceId: alliance.id, operatorId, name: target.name, from: op.name });
return { changed: true, leaderId: operatorId };
};

View file

@ -0,0 +1,35 @@
'use strict';
/* POST /diplomacy/proposals/:proposalId/accept | /decline. Needs `diplomacy` in the receiving alliance. The move is
* validated again against the CURRENT relation (it may have changed since the proposal was made). */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploAnswer(ctx, { userId, proposalId, accept }) {
const { db, now } = ctx;
const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId);
if (!p) throw new GameError('not_found', { what: 'proposal' });
const { op, alliance } = A.requireRole(db, userId, p.to_id, 'diplomacy'); // forbidden/not_found for outsiders
if (p.status !== 'pending') {
if ((accept && p.status === 'accepted') || (!accept && p.status === 'declined')) return { changed: false };
throw new GameError(p.status === 'expired' ? 'proposal_expired' : 'conflict', { what: 'proposal is ' + p.status });
}
if (p.expires_at <= now) throw new GameError('proposal_expired', { expiresAt: p.expires_at });
const proposer = A.getAlliance(db, p.from_id);
if (!proposer) throw new GameError('not_found', { what: 'alliance' });
if (!accept) {
db.run("UPDATE alliance_proposals SET status = 'declined', answered_at = ? WHERE id = ?", now, p.id);
A.notifyAlliance(ctx, proposer.id, 'diplomacy_declined', { proposalId: p.id, by: Dip.brief(alliance), state: p.state }, { roles: ['leader', 'diplomat'] });
return { changed: true };
}
const rel = A.getRelation(db, alliance.id, proposer.id);
const from = rel ? rel.state : 'neutral';
if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at });
if (R.diplomacyMove(from, p.state) !== 'proposal') throw new GameError('diplomacy_invalid', { from, to: p.state });
db.run("UPDATE alliance_proposals SET status = 'accepted', answered_at = ? WHERE id = ?", now, p.id);
Dip.applyChange(ctx, alliance, proposer, p.state, { by: op.name, proposalId: p.id });
return { changed: true, from, state: p.state };
};

View file

@ -0,0 +1,54 @@
'use strict';
/* POST /alliances/:id/diplomacy { targetId, state }. Needs `diplomacy`. What happens depends on the move
* (rules.diplomacyMove): 'immediate' applies at once (declaring war from neutral), 'delayed' schedules a cancel that
* takes 24 h / world speed (a `diploChange` event), 'proposal' asks the other alliance to accept. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { loadWorld } = require('../state');
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploPropose(ctx, { userId, allianceId, targetId, state }) {
const { db, now, scheduler } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'diplomacy');
if (targetId === alliance.id) throw new GameError('validation_failed', { errors: [{ path: 'targetId', message: 'cannot be your own alliance' }] });
const other = A.getAlliance(db, targetId);
if (!other || other.world_id !== alliance.world_id) throw new GameError('not_found', { what: 'alliance' });
const rel = A.getRelation(db, alliance.id, other.id);
const from = rel ? rel.state : 'neutral';
if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at, startedBy: rel.pending_by });
const move = R.diplomacyMove(from, state);
if (!move) throw new GameError('diplomacy_invalid', { from, to: state });
if (move === 'immediate') {
Dip.applyChange(ctx, alliance, other, state, { by: op.name });
return { result: 'applied', from, state };
}
if (move === 'delayed') {
const world = loadWorld(db, alliance.world_id);
const dueAt = now + R.pactCancelMs(world.speed);
A.withdrawProposals(db, alliance.id, other.id, now);
const eventId = scheduler.enqueue({ worldId: alliance.world_id, dueAt, type: 'diploChange', payload: { a: alliance.id, b: other.id, to: state, by: alliance.id } });
const [x, y] = A.pairOf(alliance.id, other.id);
db.run('UPDATE alliance_relations SET pending_to = ?, pending_at = ?, pending_by = ?, pending_event = ? WHERE a_id = ? AND b_id = ?', state, dueAt, alliance.id, eventId, x, y);
for (const [me, o2] of [[alliance, other], [other, alliance]]) {
A.notifyAlliance(ctx, me.id, 'diplomacy_cancel_pending', { allianceId: me.id, other: Dip.brief(o2), from, to: state, effectiveAt: dueAt, startedBy: alliance.id });
}
return { result: 'scheduled', from, state, effectiveAt: dueAt, eventId };
}
// proposal
const reverse = db.get("SELECT id, state AS st, expires_at FROM alliance_proposals WHERE from_id = ? AND to_id = ? AND status = 'pending'", other.id, alliance.id);
if (reverse && reverse.expires_at > now && reverse.st === state) throw new GameError('proposal_exists', { proposalId: reverse.id });
db.run("UPDATE alliance_proposals SET status = 'expired', answered_at = ? WHERE status = 'pending' AND expires_at <= ?", now, now);
// a new proposal from the same side replaces the old one
db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE from_id = ? AND to_id = ? AND status = 'pending'", now, alliance.id, other.id);
const expiresAt = now + Math.round(A.S.proposalTtlHours * A.HOUR);
const r = db.run('INSERT INTO alliance_proposals (world_id, from_id, to_id, state, proposed_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
alliance.world_id, alliance.id, other.id, state, op.id, now, expiresAt);
const proposalId = Number(r.lastInsertRowid);
A.notifyAlliance(ctx, other.id, 'diplomacy_proposal', { proposalId, from: Dip.brief(alliance), state, expiresAt }, { roles: ['leader', 'diplomat'] });
return { result: 'proposed', from, state, proposalId, expiresAt };
};

View file

@ -0,0 +1,22 @@
'use strict';
/* DELETE /alliances/:id/diplomacy/:otherId/pending. The alliance that started a delayed change (cancelling a pact,
* declaring war out of a pact) may take it back before it takes effect. Nothing pending: no-op. */
const { GameError } = require('../errors');
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploRevoke(ctx, { userId, allianceId, otherId }) {
const { db, now } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'diplomacy');
const other = A.getAlliance(db, otherId);
if (!other) throw new GameError('not_found', { what: 'alliance' });
const rel = A.getRelation(db, alliance.id, other.id);
if (!rel || !rel.pending_to) return { changed: false };
if (rel.pending_by !== alliance.id) throw new GameError('forbidden', { need: 'pending change started by your alliance' });
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, rel.pending_event);
db.run('UPDATE alliance_relations SET pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL WHERE a_id = ? AND b_id = ?', rel.a_id, rel.b_id);
for (const [me, o2] of [[alliance, other], [other, alliance]]) {
A.notifyAlliance(ctx, me.id, 'diplomacy_cancel_revoked', { allianceId: me.id, other: Dip.brief(o2), state: rel.state });
}
return { changed: true, state: rel.state };
};

View file

@ -0,0 +1,15 @@
'use strict';
/* DELETE /diplomacy/proposals/:proposalId. The proposing alliance withdraws it. Needs `diplomacy`. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function diploWithdraw(ctx, { userId, proposalId }) {
const { db, now } = ctx;
const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId);
if (!p) throw new GameError('not_found', { what: 'proposal' });
A.requireRole(db, userId, p.from_id, 'diplomacy');
if (p.status === 'withdrawn') return { changed: false };
if (p.status !== 'pending') throw new GameError('conflict', { what: 'proposal is ' + p.status });
db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE id = ?", now, p.id);
return { changed: true };
};

View file

@ -5,11 +5,41 @@
* scheduler timer because the command may have enqueued events.
*/
const handlers = {
// stage 3/4: military and expansion
train: require('./train'),
research: require('./research'),
sendMovement: require('./sendMovement'),
sendTransport: require('./sendTransport'),
recallMovement: require('./recallMovement'),
withdrawStationed: require('./withdrawStationed'),
markReportRead: require('./markReportRead'),
signup: require('./signup'),
joinWorld: require('./joinWorld'),
build: require('./build'),
cancelBuild: require('./cancelBuild'),
renameTown: require('./renameTown'),
// stage 5: alliances, diplomacy, messages
allianceCreate: require('./allianceCreate'),
allianceInvite: require('./allianceInvite'),
allianceInviteCancel: require('./allianceInviteCancel'),
allianceInviteAnswer: require('./allianceInviteAnswer'),
allianceLeave: require('./allianceLeave'),
allianceKick: require('./allianceKick'),
allianceRole: require('./allianceRole'),
allianceTransfer: require('./allianceTransfer'),
allianceDisband: require('./allianceDisband'),
allianceNoteAdd: require('./allianceNote').allianceNoteAdd,
allianceNoteEdit: require('./allianceNote').allianceNoteEdit,
allianceNoteDelete: require('./allianceNote').allianceNoteDelete,
diploPropose: require('./diploPropose'),
diploAnswer: require('./diploAnswer'),
diploWithdraw: require('./diploWithdraw'),
diploRevoke: require('./diploRevoke'),
messageSend: require('./messageSend'),
messageRead: require('./messageRead'),
messageDelete: require('./messageDelete'),
messageBlock: require('./messageBlock').messageBlock,
messageUnblock: require('./messageBlock').messageUnblock,
};
function createCommands({ db, clock, scheduler }) {

View file

@ -0,0 +1,14 @@
'use strict';
/* POST /reports/:id/read (and /reports/read-all). Per-user read flag; the report itself is shared. */
const { GameError } = require('../errors');
module.exports = function markReportRead(ctx, { userId, reportId, all }) {
const { db, now } = ctx;
if (all) {
const r = db.run('UPDATE report_recipients SET read_at = ? WHERE user_id = ? AND read_at IS NULL', now, userId);
return { marked: Number(r.changes) };
}
const r = db.run('UPDATE report_recipients SET read_at = COALESCE(read_at, ?) WHERE report_id = ? AND user_id = ?', now, reportId, userId);
if (!r.changes) throw new GameError('not_found', { what: 'report' });
return { marked: 1 };
};

View file

@ -0,0 +1,31 @@
'use strict';
/* POST /messages/blocks { operatorId } and DELETE /messages/blocks/:operatorId. Blocked senders' messages are not
* delivered (the sender is not told). Both idempotent. Registered as messageBlock and messageUnblock. */
const { GameError } = require('../errors');
const A = require('../alliances');
function resolve(db, userId, operatorId) {
const target = db.get('SELECT * FROM operators WHERE id = ?', operatorId);
if (!target) throw new GameError('not_found', { what: 'operator' });
const me = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, target.world_id);
if (!me) throw new GameError('not_found', { what: 'operator' });
if (me.id === target.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you cannot block yourself' }] });
return { me, target };
}
function messageBlock(ctx, { userId, operatorId }) {
const { db, now } = ctx;
const { me, target } = resolve(db, userId, operatorId);
if (db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', me.id, target.id)) return { changed: false };
if (db.get('SELECT COUNT(*) AS n FROM message_blocks WHERE operator_id = ?', me.id).n >= A.S.maxBlocks) throw new GameError('conflict', { what: 'block list full', max: A.S.maxBlocks });
db.run('INSERT INTO message_blocks (operator_id, blocked_id, created_at) VALUES (?, ?, ?)', me.id, target.id, now);
return { changed: true };
}
function messageUnblock(ctx, { userId, operatorId }) {
const { db } = ctx;
const { me, target } = resolve(db, userId, operatorId);
return { changed: db.run('DELETE FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', me.id, target.id).changes > 0 };
}
module.exports = { messageBlock, messageUnblock };

View file

@ -0,0 +1,24 @@
'use strict';
/* DELETE /messages/:id. Removes the caller's own copy only (sender copy or recipient copy). When nobody has a copy
* left the row is purged. Deleting an already deleted copy is a no-op; a message you never saw is not_found. */
const { GameError } = require('../errors');
module.exports = function messageDelete(ctx, { userId, messageId }) {
const { db, now } = ctx;
const m = db.get('SELECT m.id, m.sender_id, m.sender_deleted_at, o.user_id AS suid FROM messages m JOIN operators o ON o.id = m.sender_id WHERE m.id = ?', messageId);
if (!m) throw new GameError('not_found', { what: 'message' });
let changed = false;
if (m.suid === userId) {
changed = !m.sender_deleted_at;
if (changed) db.run('UPDATE messages SET sender_deleted_at = ? WHERE id = ?', now, m.id);
} else {
const r = db.get(`SELECT r.operator_id, r.deleted_at FROM message_recipients r JOIN operators o ON o.id = r.operator_id WHERE r.message_id = ? AND o.user_id = ?`, m.id, userId);
if (!r) throw new GameError('not_found', { what: 'message' });
changed = !r.deleted_at;
if (changed) db.run('UPDATE message_recipients SET deleted_at = ? WHERE message_id = ? AND operator_id = ?', now, m.id, r.operator_id);
}
const left = db.get(`SELECT (SELECT sender_deleted_at IS NULL FROM messages WHERE id = ?) AS s,
(SELECT COUNT(*) FROM message_recipients WHERE message_id = ? AND deleted_at IS NULL) AS r`, m.id, m.id);
if (!left.s && !left.r) { db.run('DELETE FROM message_recipients WHERE message_id = ?', m.id); db.run('DELETE FROM messages WHERE id = ?', m.id); }
return { changed };
};

View file

@ -0,0 +1,12 @@
'use strict';
/* POST /messages/read { ids } or { all: true }: mark received messages read. Already-read ones are left alone. */
module.exports = function messageRead(ctx, { userId, ids, all, worldId }) {
const { db, now } = ctx;
const ops = db.all(worldId !== undefined ? 'SELECT id FROM operators WHERE user_id = ? AND world_id = ?' : 'SELECT id FROM operators WHERE user_id = ?', userId, ...(worldId !== undefined ? [worldId] : []));
let changed = 0;
for (const o of ops) {
if (all) changed += db.run('UPDATE message_recipients SET read_at = ? WHERE operator_id = ? AND read_at IS NULL AND deleted_at IS NULL', now, o.id).changes;
else for (const id of ids || []) changed += db.run('UPDATE message_recipients SET read_at = ? WHERE operator_id = ? AND message_id = ? AND read_at IS NULL AND deleted_at IS NULL', now, o.id, id).changes;
}
return { changed: Number(changed) };
};

View file

@ -0,0 +1,72 @@
'use strict';
/* POST /messages. Player-to-player (toOperatorId | toName) or broadcast to the sender's alliance (toAlliance: true).
* Plain text, control/bidi characters stripped, at most SOCIAL.messageMax characters, rate-limited per sender by
* counting their recent rows in `messages` (DB-backed: survives restarts, follows the injected clock).
* A recipient who blocked the sender gets no row at all; the sender is not told. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { cleanText } = require('../text');
const A = require('../alliances');
const MIN = 60 * 1000;
function limit(db, senderId, kind, now) {
const L = A.S.messageLimits;
const windows = kind === 'dm' ? [[10 * MIN, L.dm10min], [60 * MIN, L.dmHour]] : [[60 * MIN, L.broadcastHour]];
for (const [ms, max] of windows) {
const r = db.get('SELECT COUNT(*) AS n, MIN(created_at) AS first FROM messages WHERE sender_id = ? AND kind = ? AND created_at > ?', senderId, kind, now - ms);
if (r.n >= max) throw new GameError('rate_limited', { retryAfter: Math.max(1, Math.ceil((r.first + ms - now) / 1000)), limit: max, windowMs: ms, scope: 'messages' });
}
}
module.exports = function messageSend(ctx, { userId, worldId, toOperatorId, toName, toAlliance, text }) {
const { db, now } = ctx;
const S = A.S;
const body = cleanText(text, { multiline: true });
if (!body || [...body].length > S.messageMax) throw new GameError('validation_failed', { errors: [{ path: 'text', message: 'must be 1-' + S.messageMax + ' characters of plain text' }] });
const targets = [toOperatorId !== undefined, toName !== undefined, !!toAlliance].filter(Boolean).length;
if (targets !== 1) throw new GameError('validation_failed', { errors: [{ path: 'toOperatorId', message: 'give exactly one of toOperatorId, toName, toAlliance' }] });
if (toAlliance) {
const me = A.operatorOf(db, userId, worldId);
const m = A.membership(db, me.id);
if (!m) throw new GameError('not_in_alliance');
if (!R.allianceCan(m.role, 'broadcast')) throw new GameError('forbidden', { need: 'broadcast', role: m.role });
limit(db, me.id, 'alliance', now);
const alliance = A.getAlliance(db, m.alliance_id);
const r = db.run('INSERT INTO messages (world_id, sender_id, kind, alliance_id, alliance_tag, thread, body, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
me.world_id, me.id, 'alliance', alliance.id, alliance.tag, 'alliance:' + alliance.id, body, now);
const id = Number(r.lastInsertRowid);
const members = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND operator_id <> ?', alliance.id, me.id);
let delivered = 0;
for (const mm of members) {
if (db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', mm.operator_id, me.id)) continue;
db.run('INSERT INTO message_recipients (message_id, operator_id) VALUES (?, ?)', id, mm.operator_id);
delivered++;
A.notifyOperator(ctx, mm.operator_id, 'alliance_message', { messageId: id, allianceId: alliance.id, tag: alliance.tag, from: me.name });
}
return { messageId: id, kind: 'alliance', recipients: delivered, createdAt: now };
}
let target;
if (toOperatorId !== undefined) target = db.get('SELECT * FROM operators WHERE id = ?', toOperatorId);
else {
const mine = A.operatorOf(db, userId, worldId); // the world the name is looked up in
target = db.get('SELECT * FROM operators WHERE name = ? COLLATE NOCASE AND world_id = ?', toName, mine.world_id);
}
if (!target) throw new GameError('not_found', { what: 'operator' });
const me = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, target.world_id);
if (!me) throw new GameError('not_found', { what: 'operator' });
if (me.id === target.id) throw new GameError('validation_failed', { errors: [{ path: 'toOperatorId', message: 'you cannot message yourself' }] });
limit(db, me.id, 'dm', now);
const lo = Math.min(me.id, target.id), hi = Math.max(me.id, target.id);
const r = db.run('INSERT INTO messages (world_id, sender_id, kind, to_id, thread, body, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
me.world_id, me.id, 'dm', target.id, 'dm:' + lo + ':' + hi, body, now);
const id = Number(r.lastInsertRowid);
const blocked = !!db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', target.id, me.id);
if (!blocked) {
db.run('INSERT INTO message_recipients (message_id, operator_id) VALUES (?, ?)', id, target.id);
A.notifyOperator(ctx, target.id, 'message', { messageId: id, from: { operatorId: me.id, name: me.name } });
}
return { messageId: id, kind: 'dm', recipients: blocked ? 0 : 1, createdAt: now };
};

View file

@ -0,0 +1,30 @@
'use strict';
/* POST /movements/:id/recall. Within the first 90 s (MILITARY.recallWindowMs) an outbound movement can turn around:
* its arrive event is cancelled and a return leg takes the same units and cargo home in as long as they were out. */
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
module.exports = function recallMovement(ctx0, { userId, movementId }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const mv = M.getMovement(db, movementId);
const op = mv && db.get('SELECT id FROM operators WHERE id = ? AND user_id = ?', mv.ownerId, userId);
if (!mv || !op) throw new GameError('not_found', { what: 'movement' });
if (mv.status !== 'out' || mv.type === 'return') throw new GameError('conflict', { what: 'movement cannot be recalled', status: mv.status, type: mv.type });
if (now - mv.departAt > D.MILITARY.recallWindowMs) throw new GameError('recall_expired', { departAt: mv.departAt, windowMs: D.MILITARY.recallWindowMs });
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
const dest = U.homeTownFor(db, mv.ownerId, origin && origin.owner_id === mv.ownerId ? origin.id : null);
if (!dest) throw new GameError('conflict', { what: 'no POP to return to' });
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, mv.eventId);
db.run("UPDATE movements SET status = 'recalled' WHERE id = ?", mv.id);
const elapsed = Math.max(1000, now - mv.departAt);
const f = Math.min(1, (now - mv.departAt) / Math.max(1, mv.arriveAt - mv.departAt));
const at = { x: Math.round(mv.from.x + (mv.to.x - mv.from.x) * f), y: Math.round(mv.from.y + (mv.to.y - mv.from.y) * f) };
const extra = Object.assign({}, mv.extra, { recalled: true });
if (mv.type === 'transport') extra.link = 1;
const ret = M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at, to: dest, units: mv.units, cargo: mv.cargo, arriveAt: now + elapsed, parentId: mv.id, extra });
return { recalled: mv.id, returnMovementId: ret.id, arriveAt: ret.arriveAt };
};

View file

@ -0,0 +1,26 @@
'use strict';
/* POST /towns/:id/research. One research at a time per POP (a `researchDone` event). +5% attack or defence per level
* of one unit type; level n needs a Research lab of level n + RESEARCH.labOffset. Incumbent sites speed it up. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { settle, spend } = require('../state');
const { ownedTown } = require('./build');
const U = require('../military/units');
module.exports = function research(ctx, { userId, townId, unit, stat }) {
const { db, now, scheduler } = ctx;
const town = ownedTown(db, userId, townId);
if (!R.unitDef(unit)) throw new GameError('unknown_unit', { unit });
settle(db, town, now);
const busy = !!db.get("SELECT 1 AS x FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' LIMIT 1", town.id);
const current = U.researchLevels(db, town.id)[R.researchKey(unit, stat)] || 0;
const plan = R.researchPlan(town, unit, stat, current, busy, now, U.researchBonusOf(db, town.ownerId));
if (!plan.ok) throw new GameError(plan.code, { unit, stat, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing });
spend(db, town, plan.cost);
const dueAt = now + plan.durationMs;
const eventId = scheduler.enqueue({
worldId: town.worldId, townId: town.id, type: 'researchDone', dueAt,
payload: { unit, stat, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId },
});
return { eventId, unit, stat, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost };
};

View file

@ -0,0 +1,120 @@
'use strict';
/*
* POST /movements. Send units from one of your POPs: scan, raid, attack, takeover, reinforce, settle. (Resources go
* through sendTransport.) Validates everything against the rules, takes the units out of the POP and enqueues the
* `arrive` event. Nothing resolves now: combat happens at arrival, in the event queue, in order.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, loadWorld } = require('../state');
const { ownedTown } = require('./build');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
const P = require('../military/power');
const TYPES = ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle'];
const HOSTILE = ['raid', 'attack', 'takeover'];
// The target of a movement: a POP (by id or by tile) or a bare tile. -> { town: row|null, x, y, tile }
function resolveTarget(db, world, args) {
let town = null, x, y;
if (args.toTownId !== undefined && args.toTownId !== null) {
town = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', args.toTownId, world.id);
if (!town) throw new GameError('not_found', { what: 'town' });
x = town.x; y = town.y;
} else if (Number.isInteger(args.x) && Number.isInteger(args.y)) {
x = args.x; y = args.y;
town = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y) || null;
} else {
throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'give toTownId or x and y' }] });
}
const tile = R.tileAt(world.seed, world.map_radius, x, y);
if (tile.type === 'void') throw new GameError('invalid_target', { reason: 'outside_map' });
return { town, x, y, tile };
}
module.exports = function sendMovement(ctx0, args) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const { userId, fromTownId, type } = args;
if (TYPES.indexOf(type) < 0) throw new GameError('validation_failed', { errors: [{ path: 'type', message: 'must be one of ' + TYPES.join(', ') }] });
const from = ownedTown(db, userId, fromTownId);
const world = loadWorld(db, from.worldId);
const op = U.getOperator(db, from.ownerId);
const units = U.cleanUnits(args.units || {});
const chk = R.checkUnitsForType(type, units);
if (chk) throw new GameError(chk.code, { reason: chk.reason });
settle(db, from, now);
const home = U.homeUnits(db, from.id);
for (const k of Object.keys(units)) if ((home[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: home[k] || 0, want: units[k] });
if (!P.online(from, now)) throw new GameError('units_offline', { townId: from.id });
const tgt = resolveTarget(db, world, args);
if (tgt.town && tgt.town.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' });
const dist = R.distance(from.x, from.y, tgt.x, tgt.y);
const arriveAt = now + R.movementMs(dist, units, world.speed);
const extra = { research: U.researchSnapshot(db, from.id, units) };
let defOp = null;
let endProtection = false;
if (type === 'scan' || HOSTILE.indexOf(type) >= 0) {
if (tgt.town) {
defOp = U.getOperator(db, tgt.town.owner_id);
if (defOp.id === op.id) throw new GameError('invalid_target', { reason: 'own_town' });
if (type !== 'scan') {
if (U.pactBlocks(db, op.id, defOp.id)) throw new GameError('invalid_target', { reason: 'pact' });
if (R.isProtected(defOp.protection_until, arriveAt)) throw new GameError('target_protected', { until: defOp.protection_until });
if (R.isProtected(op.protection_until, now)) {
if (!args.confirmEndProtection) throw new GameError('protection_active', { until: op.protection_until });
endProtection = true;
}
}
if (type === 'takeover') {
const count = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n;
const block = R.takeoverBlock(!!tgt.town.is_capital, count);
if (block === 'last_pop') throw new GameError('cannot_takeover', { reason: block });
const gate = R.footprintGate(U.operatorTowns(db, op.id).length, U.operatorFootprint(db, op.id, now));
if (!gate.ok) throw new GameError('footprint_too_low', { need: gate.need, have: gate.have });
}
} else if (tgt.tile.type === 'incumbent') {
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'incumbent_scan_or_attack_only' });
} else {
throw new GameError('invalid_target', { reason: 'nothing_there' });
}
if ((type === 'attack' || type === 'takeover') && units.exploit_kit && args.target !== undefined && args.target !== null) {
const t = String(args.target);
const bdef = R.isFieldKey(t) ? { special: false } : R.buildingDef(t);
if (!bdef || bdef.special) throw new GameError('validation_failed', { errors: [{ path: 'target', message: 'not a building' }] });
extra.target = t;
}
} else if (type === 'reinforce') {
if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' });
if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' });
defOp = U.getOperator(db, tgt.town.owner_id);
} else if (type === 'settle') {
const own = U.operatorTowns(db, op.id);
let nearest = Infinity;
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, tgt.x, tgt.y));
const chk2 = R.settleCheck({ tileType: tgt.tile.type, occupied: !!tgt.town, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
if (!chk2.ok) throw new GameError(chk2.code, chk2);
extra.wild = R.cleanWild(args.wild);
}
// ---- all checks passed: apply
if (endProtection) db.run('UPDATE operators SET protection_until = ? WHERE id = ?', now, op.id);
U.removeHome(db, from.id, units);
P.reschedule(ctx, from.id, now);
const mv = M.insertMovement(ctx, {
worldId: from.worldId, ownerId: op.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null,
from: { x: from.x, y: from.y }, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, extra,
});
if (tgt.town && defOp && defOp.id !== op.id) {
const uid = U.userOfOperator(db, defOp.id);
if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: tgt.town.id, fromTownId: from.id, arriveAt }); // type hidden
}
return { movementId: mv.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, protectionEnded: endProtection };
};
module.exports.resolveTarget = resolveTarget;

View file

@ -0,0 +1,52 @@
'use strict';
/*
* POST /movements with type 'transport': carry resources from one of your POPs to any POP. Capacity and the number
* of concurrent transports come from the Internet exchange (D.TRANSPORT): `links` = its level, each link carries
* `capacityPerLink`. The cargo leaves the POP now and is added to the target on arrival (anything above the target's
* Rack hall cap is lost). The trade stage calls `launchTransport` directly for the two legs of an accepted offer.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, loadWorld } = require('../state');
const { ownedTown } = require('./build');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
// Validate + dispatch from an already settled, owned POP `from`. `toRow` is the target POP row. `extra` is stored on
// the movement (and its return leg) for later stages, e.g. { tradeId }. Returns the movement.
function launchTransport(ctx, from, toRow, cargo, extra) {
const { db, now } = ctx;
const plan = R.transportPlan(from, cargo, M.activeLinks(db, from.id), now);
if (!plan.ok) throw new GameError(plan.code, plan);
const world = loadWorld(db, from.worldId);
const dist = R.distance(from.x, from.y, toRow.x, toRow.y);
const clean = {};
for (const r of D.RESOURCES) if (cargo[r] > 0) clean[r] = cargo[r];
for (const r of D.RESOURCES) from.res[r] -= clean[r] || 0;
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', from.res.fiber, from.res.hardware, from.res.capital, from.id);
return M.insertMovement(ctx, {
worldId: from.worldId, ownerId: from.ownerId, type: 'transport', fromTownId: from.id, toTownId: toRow.id,
from: { x: from.x, y: from.y }, to: { x: toRow.x, y: toRow.y }, units: {}, cargo: clean,
departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: Object.assign({}, extra || {}),
});
}
module.exports = function sendTransport(ctx0, { userId, fromTownId, toTownId, cargo }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const from = ownedTown(db, userId, fromTownId);
const to = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', toTownId, from.worldId);
if (!to) throw new GameError('not_found', { what: 'town' });
if (to.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' });
settle(db, from, now);
const mv = launchTransport(ctx, from, to, cargo || {});
const toOp = U.getOperator(db, to.owner_id);
if (toOp.id !== from.ownerId) {
const uid = U.userOfOperator(db, toOp.id);
if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: to.id, fromTownId: from.id, arriveAt: mv.arriveAt });
}
return { movementId: mv.id, type: 'transport', fromTownId: from.id, toTownId: to.id, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt };
};
module.exports.launchTransport = launchTransport;

37
server/commands/train.js Normal file
View file

@ -0,0 +1,37 @@
'use strict';
/*
* POST /towns/:id/train. Queue a batch of one unit type. Batches of the same training building run one after another
* (each is a `trainDone` event); different buildings train in parallel. Units appear when the batch finishes.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, spend } = require('../state');
const { ownedTown } = require('./build');
// Pending batches of a training building, in due order: [{ id, dueAt, ...payload }].
function pendingBatches(db, townId, building) {
return db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", townId)
.map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload)))
.filter((b) => !building || b.building === building);
}
module.exports = function train(ctx, { userId, townId, unit, count }) {
const { db, now, scheduler } = ctx;
const town = ownedTown(db, userId, townId);
const def = R.unitDef(unit);
if (!def) throw new GameError('unknown_unit', { unit });
settle(db, town, now);
const queue = pendingBatches(db, town.id, def.building);
if (queue.length >= D.MILITARY.maxTrainQueue) throw new GameError('queue_full', { building: def.building, max: D.MILITARY.maxTrainQueue });
const tail = queue.length ? queue[queue.length - 1].dueAt : 0;
const plan = R.trainPlan(town, unit, count, now, tail);
if (!plan.ok) throw new GameError(plan.code, { unit, count, cost: plan.cost, missing: plan.missing });
spend(db, town, plan.cost);
const eventId = scheduler.enqueue({
worldId: town.worldId, townId: town.id, type: 'trainDone', dueAt: plan.dueAt,
payload: { unit, count, building: def.building, startAt: plan.startAt, cost: plan.cost, userId },
});
return { eventId, unit, count, building: def.building, startAt: plan.startAt, dueAt: plan.dueAt, cost: plan.cost };
};
module.exports.pendingBatches = pendingBatches;

View file

@ -0,0 +1,35 @@
'use strict';
/* POST /towns/:id/withdraw. Reinforcements standing in host POP :id go home. Either side may do it: the host owner
* sends them away, the units' owner calls them back. `units` defaults to the whole group. They travel home as a
* return movement and stop drawing the host's power right away. */
const { GameError } = require('../errors');
const { settle } = require('../state');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
const P = require('../military/power');
module.exports = function withdrawStationed(ctx0, { userId, hostTownId, ownerTownId, units }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const host = db.get('SELECT * FROM towns WHERE id = ?', hostTownId);
const owner = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId);
if (!host || !owner) throw new GameError('not_found', { what: 'town' });
const mine = (t) => !!db.get('SELECT 1 AS x FROM operators WHERE id = ? AND user_id = ?', t.owner_id, userId);
if (!mine(host) && !mine(owner)) throw new GameError('not_found', { what: 'town' });
const have = U.stationedOf(db, host.id, owner.id);
let take = units && Object.keys(units).length ? U.cleanUnits(units) : have;
take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0));
if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' });
for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] });
const hostTown = require('../state').loadTown(db, host.id);
settle(db, hostTown, now); // the host's draw changes
U.removeStationed(db, host.id, owner.id, take);
P.reschedule(ctx, host.id, now);
const mv = M.launchReturn(ctx, { worldId: host.world_id, ownerId: owner.owner_id, fromTownId: host.id, at: { x: host.x, y: host.y }, to: owner, units: take, cargo: {}, extra: { withdrawn: true } });
if (!mine(owner)) {
const uid = U.userOfOperator(db, owner.owner_id);
if (uid) ctx.notify(uid, host.world_id, 'reinforcements_sent_home', { hostTownId: host.id, ownerTownId: owner.id, units: take });
}
return { movementId: mv.id, units: take, arriveAt: mv.arriveAt };
};

25
server/diplomacy.js Normal file
View file

@ -0,0 +1,25 @@
'use strict';
/* Shared pieces of the diplomacy commands and the delayed `diploChange` event. */
const A = require('./alliances');
const brief = (a) => ({ id: a.id, tag: a.tag, name: a.name });
// Everybody in both alliances hears about a relation that changed.
function announceChange(ctx, x, y, from, to, extra) {
for (const [me, other] of [[x, y], [y, x]]) {
A.notifyAlliance(ctx, me.id, 'diplomacy_changed', Object.assign({ allianceId: me.id, other: brief(other), from, to }, extra || {}));
}
}
// Make `to` the current relation of the pair right now, drop proposals that this overtakes, tell everyone.
function applyChange(ctx, x, y, to, extra) {
const { db, now } = ctx;
const cur = A.getRelation(db, x.id, y.id);
const from = cur ? cur.state : 'neutral';
A.setRelation(db, x.world_id, x.id, y.id, to, now);
A.withdrawProposals(db, x.id, y.id, now);
announceChange(ctx, x, y, from, to, extra);
return from;
}
module.exports = { brief, announceChange, applyChange };

View file

@ -28,6 +28,34 @@ const CODES = {
already_queued: [409, 'That building is already being built.'],
queue_full: [409, 'All build slots are busy.'],
not_enough_resources: [409, 'Not enough resources.'],
// social: alliances, diplomacy, messages
peering_office_required: [409, 'A Peering office (level 1 or higher) is needed to found or join an alliance.'],
already_in_alliance: [409, 'That operator is already in an alliance.'],
not_in_alliance: [409, 'You are not in that alliance.'],
alliance_name_taken: [409, 'That alliance name is taken.'],
alliance_tag_taken: [409, 'That alliance tag is taken.'],
alliance_full: [409, 'The alliance has no room for more members.'],
invite_expired: [409, 'The invite has expired.'],
leader_must_transfer: [409, 'The leader must hand over leadership before leaving.'],
notes_full: [409, 'The alliance has reached its pinned-note limit.'],
diplomacy_invalid: [409, 'That diplomatic move is not allowed from the current state.'],
diplomacy_pending: [409, 'A diplomatic change between these alliances is already scheduled.'],
proposal_exists: [409, 'The other alliance already proposed this; accept their proposal instead.'],
proposal_expired: [409, 'The proposal has expired.'],
// military and expansion
unknown_unit: [404, 'No such unit type.'],
not_researchable: [409, 'That unit stat cannot be researched.'],
not_enough_units: [409, 'Not enough units at home.'],
units_offline: [409, 'Those units are offline (the battery is empty).'],
invalid_target: [409, 'That target is not valid for this kind of movement.'],
target_protected: [409, 'The target is under beginner protection.'],
protection_active: [409, 'Attacking ends your beginner protection; confirm to go ahead.'],
out_of_range: [409, 'The target is too far from your POPs.'],
footprint_too_low: [409, 'Your footprint is too low for another POP.'],
cannot_takeover: [409, 'That POP cannot be taken over.'],
recall_expired: [409, 'The recall window (first 90 seconds) has passed.'],
capacity_exceeded: [409, 'More than one transport link can carry.'],
no_transport_link: [409, 'All transport links are busy (or there is no Internet exchange).'],
};
class GameError extends Error {

19
server/events/arrive.js Normal file
View file

@ -0,0 +1,19 @@
'use strict';
/* A movement reached its destination. Payload { movementId }. Dispatches by movement type; everything runs at the
* event's own due time, inside the scheduler's transaction. Idempotent: only an `out` movement is processed. */
const M = require('../military/movements');
const A = require('../military/arrivals');
const combat = require('../military/combat');
module.exports = function arrive(ctx, ev) {
const mv = M.getMovement(ctx.db, ev.payload.movementId);
if (!mv || mv.status !== 'out') return;
ctx.db.run("UPDATE movements SET status = 'done' WHERE id = ?", mv.id);
switch (mv.type) {
case 'scan': case 'raid': case 'attack': case 'takeover': return combat.arrive(ctx, mv, ev);
case 'reinforce': return A.arriveReinforce(ctx, mv, ev);
case 'transport': return A.arriveTransport(ctx, mv, ev);
case 'settle': return A.arriveSettle(ctx, mv, ev);
default: throw new Error('unknown movement type ' + mv.type);
}
};

View file

@ -11,5 +11,6 @@ module.exports = function buildDone(ctx, ev) {
const cur = town.buildings[key];
if (!cur) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, toLevel);
else if (cur.level < toLevel) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', toLevel, town.id, key);
require('../military/power').reschedule(ctx, town.id, ev.dueAt); // building draw / battery cap changed: units' power check
if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel });
};

View file

@ -0,0 +1,15 @@
'use strict';
/* A unilateral cancel of a pact (or war declared out of a pact) came due. Payload { a, b, to, by }.
* Idempotent and safe against cancellation: it only acts when the relation row still points at THIS event. */
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploChange(ctx, ev) {
const { db } = ctx;
const { a, b, to } = ev.payload;
const rel = A.getRelation(db, a, b);
if (!rel || rel.pending_event !== ev.id) return; // revoked, replaced, or already applied
const x = A.getAlliance(db, a), y = A.getAlliance(db, b);
if (!x || !y) return;
Dip.applyChange(ctx, x, y, to, { delayed: true, startedBy: ev.payload.by });
};

View file

@ -1,5 +1,13 @@
'use strict';
/* Event type -> handler. One file per event type. */
module.exports = {
// stage 3/4: military and expansion
trainDone: require('./trainDone'),
researchDone: require('./researchDone'),
arrive: require('./arrive'),
return: require('./return'),
powerCheck: require('./powerCheck'),
reportCleanup: require('./reportCleanup'),
buildDone: require('./buildDone'),
diploChange: require('./diploChange'),
};

View file

@ -0,0 +1,3 @@
'use strict';
/* Battery empty / offline for 24 h: see server/military/power.js. Payload { townId }. */
module.exports = require('../military/power').powerCheck;

View file

@ -0,0 +1,9 @@
'use strict';
/* Delete expired reports (14 days, real time), then arm the next cleanup for the earliest remaining expiry. createReport
* arms it when none is pending, so there is at most one pending cleanup per world and none while no reports exist. */
module.exports = function reportCleanup(ctx, ev) {
const { db } = ctx;
db.run('DELETE FROM reports WHERE world_id = ? AND expires_at <= ?', ev.worldId, ev.dueAt);
const left = db.get('SELECT MIN(expires_at) AS e FROM reports WHERE world_id = ?', ev.worldId);
if (left && left.e !== null) ctx.enqueue({ worldId: ev.worldId, dueAt: left.e, type: 'reportCleanup', payload: { worldId: ev.worldId } });
};

View file

@ -0,0 +1,12 @@
'use strict';
/* A research level finished. Payload { unit, stat, toLevel, userId }. Idempotent: a level never goes down. */
const R = require('../../public/js/rules.js');
module.exports = function researchDone(ctx, ev) {
const { db } = ctx;
const { unit, stat, toLevel, userId } = ev.payload;
if (!db.get('SELECT 1 AS x FROM towns WHERE id = ?', ev.townId)) return;
db.run(`INSERT INTO town_research (town_id, unit, stat, level) VALUES (?, ?, ?, ?)
ON CONFLICT (town_id, unit, stat) DO UPDATE SET level = MAX(level, excluded.level)`, ev.townId, unit, stat, toLevel);
if (userId) ctx.notify(userId, ev.worldId, 'research_done', { townId: ev.townId, unit, stat, level: toLevel, key: R.researchKey(unit, stat) });
};

28
server/events/return.js Normal file
View file

@ -0,0 +1,28 @@
'use strict';
/*
* A return leg arrived: units and cargo go back home. If the origin POP changed hands meanwhile they go to the
* operator's capital (or oldest POP) instead; with no POP left they are lost. Cargo above the Rack hall cap is lost.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { loadTown, settle } = require('../state');
const M = require('../military/movements');
const U = require('../military/units');
const P = require('../military/power');
const { addCargo } = require('../military/arrivals');
module.exports = function ret(ctx, ev) {
const { db } = ctx;
const mv = M.getMovement(db, ev.payload.movementId);
if (!mv || mv.status !== 'out') return;
db.run("UPDATE movements SET status = 'done' WHERE id = ?", mv.id);
const dest = U.homeTownFor(db, mv.ownerId, mv.toTownId);
const uid = U.userOfOperator(db, mv.ownerId);
if (!dest) { if (uid) ctx.notify(uid, mv.worldId, 'movement_lost', { movementId: mv.id }); return; }
const town = loadTown(db, dest.id);
settle(db, town, ev.dueAt);
U.addHome(db, town.id, mv.units);
const lost = addCargo(db, town, mv.cargo);
P.reschedule(ctx, town.id, ev.dueAt);
if (uid && !mv.extra.link) ctx.notify(uid, mv.worldId, 'movement_returned', { movementId: mv.id, townId: town.id, units: mv.units, cargo: mv.cargo, cargoLost: lost });
};

View file

@ -0,0 +1,17 @@
'use strict';
/* A training batch finished. Payload { unit, count, building, userId }. The POP is settled to the due time at the OLD
* power draw, then the units appear (and the draw rises). */
const { loadTown, settle } = require('../state');
const U = require('../military/units');
const P = require('../military/power');
module.exports = function trainDone(ctx, ev) {
const { db } = ctx;
const { unit, count, userId } = ev.payload;
const town = loadTown(db, ev.townId);
if (!town) return;
settle(db, town, ev.dueAt);
U.addHome(db, town.id, { [unit]: count });
P.reschedule(ctx, town.id, ev.dueAt);
if (userId) ctx.notify(userId, ev.worldId, 'train_done', { townId: town.id, unit, count });
};

View file

@ -17,7 +17,7 @@ const { TokenBucket, clientIp } = require('./net');
const { applySecurityHeaders } = require('./static');
const MAX_BODY = 32 * 1024;
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId']);
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId']);
// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound.
class Limiter {

View file

@ -0,0 +1,102 @@
-- Stage 3/4 (military, expansion): units at home, reinforcements, research, movements, reports, battle points.
-- Units are { unit id: count } everywhere. Times are integer ms since the epoch (UTC).
-- Units at home, owned by the town's owner. Always settle() the town before changing these (power draw changes).
CREATE TABLE town_units (
town_id INTEGER NOT NULL REFERENCES towns(id),
unit TEXT NOT NULL,
count INTEGER NOT NULL CHECK (count > 0),
PRIMARY KEY (town_id, unit)
);
-- Reinforcements: units of owner_town_id's operator standing in host_town_id. They defend the host and draw its power.
CREATE TABLE stationed (
host_town_id INTEGER NOT NULL REFERENCES towns(id),
owner_town_id INTEGER NOT NULL REFERENCES towns(id),
unit TEXT NOT NULL,
count INTEGER NOT NULL CHECK (count > 0),
PRIMARY KEY (host_town_id, owner_town_id, unit)
);
CREATE INDEX stationed_owner ON stationed(owner_town_id);
-- Research levels per POP (attack or defence of one unit type).
CREATE TABLE town_research (
town_id INTEGER NOT NULL REFERENCES towns(id),
unit TEXT NOT NULL,
stat TEXT NOT NULL, -- attack | defence
level INTEGER NOT NULL,
PRIMARY KEY (town_id, unit, stat)
);
-- When the units in a POP went offline (battery empty, net power negative). NULL / no row = online.
CREATE TABLE town_power (
town_id INTEGER PRIMARY KEY REFERENCES towns(id),
offline_since INTEGER
);
-- Everything that is travelling. type: scan | raid | attack | takeover | reinforce | settle | transport | return.
-- status: out (travelling, arrive/return event pending) | done | recalled (turned around, a return movement exists).
-- A target is a POP (to_town_id) or just a tile (settle, incumbent sites): to_x/to_y are always set.
CREATE TABLE movements (
id INTEGER PRIMARY KEY,
world_id INTEGER NOT NULL REFERENCES worlds(id),
owner_id INTEGER NOT NULL REFERENCES operators(id),
type TEXT NOT NULL,
from_town_id INTEGER REFERENCES towns(id),
to_town_id INTEGER REFERENCES towns(id),
from_x INTEGER NOT NULL,
from_y INTEGER NOT NULL,
to_x INTEGER NOT NULL,
to_y INTEGER NOT NULL,
units TEXT NOT NULL DEFAULT '{}',
cargo TEXT NOT NULL DEFAULT '{}',
depart_at INTEGER NOT NULL,
arrive_at INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'out',
event_id INTEGER,
parent_id INTEGER, -- the outbound movement a return belongs to
extra TEXT NOT NULL DEFAULT '{}', -- research snapshot, building target, wild slots, trade metadata, ...
created_at INTEGER NOT NULL
);
CREATE INDEX movements_owner ON movements(owner_id, status);
CREATE INDEX movements_to ON movements(to_town_id, status);
CREATE INDEX movements_from ON movements(from_town_id, status);
-- A report is one row, shared by all participants (report_recipients). Kept 14 days (expires_at), cleaned by an event.
CREATE TABLE reports (
id INTEGER PRIMARY KEY,
world_id INTEGER NOT NULL REFERENCES worlds(id),
type TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
summary TEXT NOT NULL DEFAULT '{}',
data TEXT NOT NULL DEFAULT '{}'
);
CREATE INDEX reports_expires ON reports(expires_at);
CREATE TABLE report_recipients (
report_id INTEGER NOT NULL REFERENCES reports(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id),
role TEXT NOT NULL, -- attacker | defender | reinforcer | sender | target
read_at INTEGER,
PRIMARY KEY (report_id, user_id)
);
CREATE INDEX report_recipients_user ON report_recipients(user_id, report_id);
-- Battle points per operator, written by combat; rankings (social) read it.
CREATE TABLE operator_stats (
operator_id INTEGER PRIMARY KEY REFERENCES operators(id),
attack_points REAL NOT NULL DEFAULT 0,
defense_points REAL NOT NULL DEFAULT 0
);
-- Incumbent sites an operator has taken (one-time Hardware bonus per site; the count drives the research speed bonus).
CREATE TABLE incumbent_takes (
world_id INTEGER NOT NULL REFERENCES worlds(id),
x INTEGER NOT NULL,
y INTEGER NOT NULL,
operator_id INTEGER NOT NULL REFERENCES operators(id),
taken_at INTEGER NOT NULL,
PRIMARY KEY (world_id, x, y, operator_id)
);
CREATE INDEX incumbent_takes_operator ON incumbent_takes(operator_id);

View file

@ -0,0 +1,113 @@
-- Stage 5 (social): alliances, diplomacy between alliances, pinned notes, messages.
-- operators.alliance_id (001) stays the quick lookup; alliance_members adds the role and is kept in step with it by
-- server/alliances.js (addMember / removeMember are the only writers).
CREATE TABLE alliances (
id INTEGER PRIMARY KEY,
world_id INTEGER NOT NULL REFERENCES worlds(id),
name TEXT NOT NULL COLLATE NOCASE,
tag TEXT NOT NULL COLLATE NOCASE,
size_cap INTEGER NOT NULL, -- stored at founding, only ever raised (rules.allianceCap)
created_by INTEGER NOT NULL REFERENCES operators(id),
created_at INTEGER NOT NULL,
UNIQUE (world_id, name),
UNIQUE (world_id, tag)
);
CREATE TABLE alliance_members (
operator_id INTEGER PRIMARY KEY REFERENCES operators(id),
alliance_id INTEGER NOT NULL REFERENCES alliances(id),
role TEXT NOT NULL, -- leader | diplomat | officer | member
joined_at INTEGER NOT NULL
);
CREATE INDEX alliance_members_alliance ON alliance_members(alliance_id);
CREATE UNIQUE INDEX alliance_one_leader ON alliance_members(alliance_id) WHERE role = 'leader';
CREATE TABLE alliance_invites (
id INTEGER PRIMARY KEY,
alliance_id INTEGER NOT NULL REFERENCES alliances(id),
operator_id INTEGER NOT NULL REFERENCES operators(id), -- the invitee
invited_by INTEGER NOT NULL REFERENCES operators(id),
status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | cancelled | expired
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
answered_at INTEGER
);
CREATE UNIQUE INDEX alliance_invites_pending ON alliance_invites(alliance_id, operator_id) WHERE status = 'pending';
CREATE INDEX alliance_invites_operator ON alliance_invites(operator_id, status);
CREATE TABLE alliance_notes (
id INTEGER PRIMARY KEY,
alliance_id INTEGER NOT NULL REFERENCES alliances(id),
author_id INTEGER NOT NULL REFERENCES operators(id),
text TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX alliance_notes_alliance ON alliance_notes(alliance_id, id);
-- One row per alliance pair that is not plainly neutral (a_id < b_id). state = the CURRENT relation. A unilateral cancel
-- keeps `state` until the delayed `diploChange` event (pending_event) applies pending_to at pending_at.
CREATE TABLE alliance_relations (
a_id INTEGER NOT NULL REFERENCES alliances(id),
b_id INTEGER NOT NULL REFERENCES alliances(id),
world_id INTEGER NOT NULL,
state TEXT NOT NULL, -- war | neutral | nap | confed
since INTEGER NOT NULL,
pending_to TEXT,
pending_at INTEGER,
pending_by INTEGER, -- the alliance that started the change
pending_event INTEGER, -- events.id
PRIMARY KEY (a_id, b_id),
CHECK (a_id < b_id)
);
CREATE INDEX alliance_relations_b ON alliance_relations(b_id);
CREATE TABLE alliance_proposals (
id INTEGER PRIMARY KEY,
world_id INTEGER NOT NULL,
from_id INTEGER NOT NULL REFERENCES alliances(id),
to_id INTEGER NOT NULL REFERENCES alliances(id),
state TEXT NOT NULL, -- the proposed relation
status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | withdrawn | expired
proposed_by INTEGER NOT NULL REFERENCES operators(id),
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
answered_at INTEGER
);
CREATE UNIQUE INDEX alliance_proposals_pending ON alliance_proposals(from_id, to_id) WHERE status = 'pending';
CREATE INDEX alliance_proposals_to ON alliance_proposals(to_id, status);
-- Messages. No foreign key on alliance_id: broadcasts outlive a disbanded alliance (alliance_tag is a snapshot).
-- Each recipient has their own row (read / deleted); the sender's copy is hidden with sender_deleted_at.
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
world_id INTEGER NOT NULL,
sender_id INTEGER NOT NULL REFERENCES operators(id),
kind TEXT NOT NULL, -- dm | alliance
to_id INTEGER REFERENCES operators(id), -- dm only
alliance_id INTEGER, -- alliance broadcast only
alliance_tag TEXT,
thread TEXT NOT NULL, -- 'dm:<lowId>:<highId>' | 'alliance:<id>'
body TEXT NOT NULL,
created_at INTEGER NOT NULL,
sender_deleted_at INTEGER
);
CREATE INDEX messages_sender ON messages(sender_id, id);
CREATE INDEX messages_thread ON messages(thread, id);
CREATE TABLE message_recipients (
message_id INTEGER NOT NULL REFERENCES messages(id),
operator_id INTEGER NOT NULL REFERENCES operators(id),
read_at INTEGER,
deleted_at INTEGER,
PRIMARY KEY (message_id, operator_id)
);
CREATE INDEX message_recipients_operator ON message_recipients(operator_id, message_id);
CREATE TABLE message_blocks (
operator_id INTEGER NOT NULL REFERENCES operators(id), -- who blocks
blocked_id INTEGER NOT NULL REFERENCES operators(id),
created_at INTEGER NOT NULL,
PRIMARY KEY (operator_id, blocked_id)
);

122
server/military/arrivals.js Normal file
View file

@ -0,0 +1,122 @@
'use strict';
/*
* Arrival handlers for the movements that are not fights: reinforce, transport, settle. Plus the shared pieces every
* arrival uses (cargo delivery, bouncing a movement back, brief descriptions for reports). Each handler runs inside the
* `arrive` event's transaction at the event's own due time.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { loadTown, settle, loadWorld } = require('../state');
const { createTown } = require('../commands/joinWorld');
const U = require('./units');
const M = require('./movements');
const P = require('./power');
const { createReport } = require('./reports');
const townBrief = (t) => t ? { id: t.id, name: t.name, x: t.x, y: t.y } : null;
const opBrief = (o) => o ? { id: o.id, name: o.name, asNumber: o.as_number } : null;
// Add resources to a SETTLED town, capped at its storage (an amount already above the cap is kept). -> what was lost
function addCargo(db, town, cargo) {
const cap = R.storageCap(town);
const lost = {};
for (const r of D.RESOURCES) {
const add = (cargo && cargo[r]) || 0;
if (!add) continue;
const cur = town.res[r];
const next = Math.min(Math.max(cap, cur), cur + add);
lost[r] = Math.max(0, Math.round(cur + add - next));
town.res[r] = next;
}
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
return lost;
}
// The movement cannot do what it came for: its units (and cargo) turn around and a report tells the sender why.
function bounce(ctx, mv, now, reason, details) {
const { db } = ctx;
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
if (dest && !U.isEmpty(mv.units)) {
M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: mv.units, cargo: mv.cargo, parentId: mv.id, extra: { bounced: reason } });
}
createReport(ctx, {
worldId: mv.worldId, type: 'movement_failed', now,
summary: { movementType: mv.type, reason, to: mv.to },
data: { movementType: mv.type, reason, details: details || {}, to: mv.to, units: mv.units },
recipients: [{ userId: U.userOfOperator(db, mv.ownerId), role: 'sender' }],
});
}
function arriveReinforce(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
const target = mv.toTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId) : null;
if (!target || !U.mayReinforce(db, mv.ownerId, target.owner_id)) return bounce(ctx, mv, now, 'not_allied');
const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to
const host = loadTown(db, target.id);
settle(db, host, now); // the host's draw rises at this moment
// Moving units between your own POPs: they simply live in the new POP now. Only other operators' units are "stationed".
if (ownerTown.id === host.id || target.owner_id === mv.ownerId) U.addHome(db, host.id, mv.units);
else U.addStationed(db, host.id, ownerTown.id, mv.units);
P.reschedule(ctx, host.id, now);
const sender = U.getOperator(db, mv.ownerId), hostOp = U.getOperator(db, target.owner_id);
createReport(ctx, {
worldId: mv.worldId, type: 'reinforce', now,
summary: { host: townBrief(target), from: townBrief(ownerTown), units: mv.units },
data: { host: townBrief(target), hostOperator: opBrief(hostOp), from: townBrief(ownerTown), operator: opBrief(sender), units: mv.units },
recipients: [{ userId: U.userOfOperator(db, sender.id), role: 'sender' }, { userId: U.userOfOperator(db, hostOp.id), role: 'target' }],
});
}
function arriveTransport(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
const target = mv.toTownId ? loadTown(db, mv.toTownId) : null;
let lost = {};
if (target) {
settle(db, target, now);
lost = addCargo(db, target, mv.cargo);
const sender = U.userOfOperator(db, mv.ownerId), receiver = U.userOfOperator(db, target.ownerId);
if (receiver) ctx.notify(receiver, mv.worldId, 'transport_arrived', { movementId: mv.id, townId: target.id, fromTownId: mv.fromTownId, cargo: mv.cargo, cargoLost: lost, own: receiver === sender });
if (sender && sender !== receiver) ctx.notify(sender, mv.worldId, 'transport_delivered', { movementId: mv.id, toTownId: target.id, cargo: mv.cargo, cargoLost: lost });
for (const fn of M.hooks.transportArrived) fn(ctx, mv, { added: mv.cargo, lost });
}
const cargoBack = target ? {} : mv.cargo; // no such POP any more: the cargo rides home with the carriers
// The empty carriers drive back; the link is busy until they are home.
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
if (dest) {
const world = loadWorld(db, mv.worldId);
const dist = R.distance(mv.to.x, mv.to.y, dest.x, dest.y);
M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: {}, cargo: cargoBack, arriveAt: now + R.transportMs(dist, world.speed), parentId: mv.id, extra: Object.assign({}, mv.extra, { link: 1 }) });
}
}
// Three Rollout crews found a new POP on the empty tile, if it is still empty land, still in range, footprint still enough.
function arriveSettle(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
const world = loadWorld(db, mv.worldId);
const op = U.getOperator(db, mv.ownerId);
const { x, y } = mv.to;
const tile = R.tileAt(world.seed, world.map_radius, x, y);
const occupied = !!db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
const own = U.operatorTowns(db, op.id);
let nearest = Infinity;
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
const chk = R.settleCheck({ tileType: tile.type, occupied, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
if (!chk.ok) return bounce(ctx, mv, now, chk.code, chk);
const wild = R.cleanWild(mv.extra.wild);
const name = op.name + ' POP ' + (own.length + 1);
const id = createTown(db, { worldId: world.id, ownerId: op.id, name, x, y, isCapital: false, now, buildings: R.newTownBuildings(wild), res: D.EXPANSION.startResources });
db.run('UPDATE towns SET battery = 0, loyalty = ? WHERE id = ?', D.EXPANSION.foundedLoyalty, id);
const founded = { id, name, x, y };
createReport(ctx, {
worldId: world.id, type: 'settle', now,
summary: { success: true, town: founded },
data: { success: true, town: founded, wild, crews: mv.units, from: mv.fromTownId },
recipients: [{ userId: U.userOfOperator(db, op.id), role: 'sender' }],
});
}
module.exports = { addCargo, bounce, arriveReinforce, arriveTransport, arriveSettle, townBrief, opBrief };

282
server/military/combat.js Normal file
View file

@ -0,0 +1,282 @@
'use strict';
/*
* Arrival of scan / raid / attack / takeover. Everything here runs inside the `arrive` event's transaction at the
* event's own due time, after every earlier event, so combat order is exactly event order. Deterministic: the only
* dice (the loyalty roll) are seeded from (world seed, movement id).
*
* Steps: re-check the target (it may have changed since departure) -> settle the target to the due time -> gather
* defenders (home crews + reinforcements, only while online) -> rules.resolveBattle -> apply losses, loot, siege,
* takeover -> survivors drive home with the loot -> reports + battle points.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { loadTown, settle, loadWorld } = require('../state');
const U = require('./units');
const M = require('./movements');
const P = require('./power');
const { createReport } = require('./reports');
const { bounce, townBrief, opBrief } = require('./arrivals');
const DAY = 24 * D.HOUR_MS;
// All groups standing in the target: home crews then each reinforcing POP's units, with the research that applies.
function defenderGroups(db, target) {
const groups = [];
const home = U.homeUnits(db, target.id);
if (!U.isEmpty(home)) groups.push({ id: 'home', ownerTownId: target.id, ownerOpId: target.ownerId, units: home, research: U.researchLevels(db, target.id) });
for (const g of U.hostedGroups(db, target.id)) {
const ot = db.get('SELECT owner_id FROM towns WHERE id = ?', g.ownerTownId);
groups.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: ot ? ot.owner_id : null, units: g.units, research: U.researchLevels(db, g.ownerTownId) });
}
return groups;
}
// Write a defending group's units back after the battle.
function writeGroup(db, hostTownId, group, units) {
const keys = new Set(Object.keys(group.units).concat(Object.keys(units)));
for (const k of keys) {
if (group.id === 'home') U.setHomeUnit(db, hostTownId, k, units[k] || 0);
else U.setStationed(db, hostTownId, group.ownerTownId, k, units[k] || 0);
}
}
function addPoints(db, operatorId, column, v) {
if (!operatorId || !(v > 0)) return;
db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 0, 0) ON CONFLICT (operator_id) DO NOTHING', operatorId);
db.run('UPDATE operator_stats SET ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' = ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' + ? WHERE operator_id = ?', v, operatorId);
}
const sumValues = (list) => list.reduce((acc, u) => U.sumInto(acc, u), {});
// Survivors drive home (with loot). No survivors, no movement.
function sendHome(ctx, mv, survivors, cargo) {
const { db } = ctx;
if (U.isEmpty(survivors)) return null;
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
if (!dest) return null;
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: {} });
}
function arrive(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
const world = loadWorld(db, mv.worldId);
if (!mv.toTownId) return arriveSite(ctx, mv, now, world);
const targetRow = db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId);
if (!targetRow) return bounce(ctx, mv, now, 'target_gone');
const attackerOp = U.getOperator(db, mv.ownerId);
const defOp = U.getOperator(db, targetRow.owner_id);
if (defOp.id === attackerOp.id) return bounce(ctx, mv, now, 'own_town');
if (mv.type !== 'scan') {
if (R.isProtected(defOp.protection_until, now)) return bounce(ctx, mv, now, 'protected', { until: defOp.protection_until });
if (U.pactBlocks(db, attackerOp.id, defOp.id)) return bounce(ctx, mv, now, 'pact');
}
const target = loadTown(db, targetRow.id);
settle(db, target, now);
const online = P.online(target, now);
const groups = defenderGroups(db, target);
const active = online ? groups : [];
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
if (mv.type === 'scan') return resolveScanOnTown(ctx, mv, now, { target, targetRow, defOp, attackerOp, origin, groups, active, online });
const kind = mv.type === 'raid' ? 'raid' : 'attack';
const fwLevel = target.buildings.firewall ? target.buildings.firewall.level : 0;
const b = R.resolveBattle({
kind, attackers: { units: mv.units, research: mv.extra.research || {} },
defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: fwLevel,
});
const win = b.attackerWins;
// ---- defenders: losses (a full attack lost by the defender wipes everything in the POP, offline units included)
const wipe = b.defenderLossFraction >= 1;
const groupReports = [];
let defenderLost = {};
for (const g of groups) {
const res = b.defenders.find((d) => d.id === g.id);
let survivors, lost;
if (wipe) { survivors = {}; lost = g.units; }
else if (res) { survivors = res.survivors; lost = res.lost; }
else { survivors = g.units; lost = {}; } // offline and not wiped: untouched
writeGroup(db, target.id, g, survivors);
U.sumInto(defenderLost, lost);
groupReports.push({ id: g.id, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors, share: res ? res.share : 0, offline: !res });
}
const survivorsAtt = Object.assign({}, b.attacker.survivors);
// ---- loot
let loot = { fiber: 0, hardware: 0, capital: 0 };
let hidden = 0;
if (win) {
hidden = kind === 'raid' ? R.cacheFraction(target.buildings.rack_hall ? target.buildings.rack_hall.level : 0) : 0;
const avail = {};
for (const r of D.RESOURCES) avail[r] = target.res[r] * (1 - hidden);
loot = R.lootSplit(R.carryOf(survivorsAtt), avail);
for (const r of D.RESOURCES) target.res[r] -= loot[r];
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', target.res.fiber, target.res.hardware, target.res.capital, target.id);
}
// ---- siege: exploit kits tear levels off the chosen building
let siege = null;
if (win && mv.type !== 'raid' && mv.extra.target) {
const levels = R.siegeLevels(survivorsAtt.exploit_kit || 0);
const cur = levels > 0 ? target.buildings[mv.extra.target] : null;
if (cur && cur.level > 0) {
const to = Math.max(0, cur.level - levels);
db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', to, target.id, mv.extra.target);
siege = { key: mv.extra.target, type: cur.type, from: cur.level, to };
}
}
// ---- takeover
let takeover = null;
let captured = false;
if (mv.type === 'takeover' && win && (survivorsAtt[D.EXPANSION.conquestUnit] || 0) > 0) {
const defTowns = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n;
const block = R.takeoverBlock(!!targetRow.is_capital, defTowns);
const gate = R.footprintGate(U.operatorTowns(db, attackerOp.id).length, U.operatorFootprint(db, attackerOp.id, now));
takeover = { attempted: true, blocked: block === 'last_pop' ? 'last_pop' : (gate.ok ? null : 'footprint'), capital: block === 'capital', loyaltyBefore: target.loyalty, loyaltyAfter: target.loyalty, drop: 0, captured: false };
if (takeover.blocked === null) {
const rand = R.rng(R.hash(world.seed, mv.id, 0x7a11))();
const drop = R.loyaltyDrop(rand);
const after = Math.max(0, target.loyalty - drop);
const left = survivorsAtt[D.EXPANSION.conquestUnit] - 1; // the M&A team that did the talking is used up
if (left > 0) survivorsAtt[D.EXPANSION.conquestUnit] = left; else delete survivorsAtt[D.EXPANSION.conquestUnit];
db.run('UPDATE towns SET loyalty = ?, loyalty_at = ? WHERE id = ?', after, now, target.id);
Object.assign(takeover, { drop, loyaltyAfter: after });
if (after <= 0 && block === null) { transferTown(ctx, target, attackerOp, defOp, now); captured = true; takeover.captured = true; }
}
}
// ---- battle points
const attLost = b.attacker.lost;
addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost));
const defPts = R.battlePoints(attLost);
for (const g of groupReports) addPoints(db, g.ownerOpId, 'defense', defPts * g.share);
P.reschedule(ctx, target.id, now);
const ret = sendHome(ctx, mv, survivorsAtt, loot);
// ---- reports
const data = {
type: mv.type, outcome: win ? 'attacker_won' : 'defender_won', arrivedAt: now,
attacker: { operator: opBrief(attackerOp), town: townBrief(origin), units: { sent: mv.units, lost: attLost, survivors: survivorsAtt } },
defender: { operator: opBrief(defOp), town: townBrief(target), online, groups: groupReports.map((g) => ({ ownerTownId: g.ownerTownId, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) },
power: { attack: b.A, defence: b.D, defenceRaw: b.defenceRaw, firewallLevel: fwLevel, effectiveFirewall: b.effectiveFirewall },
loot, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null,
};
const summary = { type: mv.type, outcome: data.outcome, attacker: opBrief(attackerOp), defender: opBrief(defOp), target: townBrief(target), loot, captured };
const recipients = [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }, { userId: U.userOfOperator(db, defOp.id), role: 'defender' }];
for (const g of groupReports) if (g.id !== 'home' && g.ownerOpId) recipients.push({ userId: U.userOfOperator(db, g.ownerOpId), role: 'reinforcer' });
createReport(ctx, { worldId: mv.worldId, type: mv.type, now, summary, data, recipients });
}
// ---- scans
function resolveScanOnTown(ctx, mv, now, s) {
const { db } = ctx;
const { target, defOp, attackerOp, origin, groups, active, online } = s;
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
let sd = 0;
for (const g of active) sd += R.scanStrength(g.units.port_scanner || 0, g.research);
const res = R.resolveScan(sa, sd);
const loss = R.applyLoss(mv.units, res.lossFraction);
let intel = null;
if (res.success) {
intel = {
detail: res.detail, online,
units: { home: U.homeUnits(db, target.id), stationed: groups.filter((g) => g.id !== 'home').map((g) => ({ ownerTownId: g.ownerTownId, units: g.units })) },
resources: { fiber: target.res.fiber, hardware: target.res.hardware, capital: target.res.capital },
};
if (res.detail === 'full') {
intel.buildings = Object.keys(target.buildings).map((k) => ({ key: k, type: target.buildings[k].type, level: target.buildings[k].level }));
intel.loyalty = target.loyalty;
intel.outgoing = db.all("SELECT id, type, to_x, to_y, arrive_at FROM movements WHERE from_town_id = ? AND status = 'out' AND type != 'return' ORDER BY arrive_at, id", target.id)
.map((m) => ({ type: m.type, to: { x: m.to_x, y: m.to_y }, arriveAt: m.arrive_at }));
}
}
const aData = { success: res.success, detail: res.detail, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, strength: { attacker: sa, defender: sd }, target: townBrief(target), operator: opBrief(defOp), intel };
createReport(ctx, {
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, target: townBrief(target), operator: opBrief(defOp) },
data: aData, recipients: [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }],
});
const dData = { identityRevealed: res.identityRevealed, target: townBrief(target), by: res.identityRevealed ? { operator: opBrief(attackerOp), town: townBrief(origin) } : null };
createReport(ctx, {
worldId: mv.worldId, type: 'scan_detected', now, summary: { identityRevealed: res.identityRevealed, target: townBrief(target), by: dData.by && dData.by.operator },
data: dData, recipients: [{ userId: U.userOfOperator(db, defOp.id), role: 'defender' }],
});
sendHome(ctx, mv, loss.survivors, {});
}
// ---- incumbent sites (NPC): static defence, no losses for the site, never attack
function arriveSite(ctx, mv, now, world) {
const { db } = ctx;
const { x, y } = mv.to;
const tile = R.tileAt(world.seed, world.map_radius, x, y);
if (tile.type !== 'incumbent' || (mv.type !== 'scan' && mv.type !== 'attack')) return bounce(ctx, mv, now, 'invalid_target');
const attackerOp = U.getOperator(db, mv.ownerId);
const ageDays = Math.max(0, (now - world.start_at) / DAY * world.speed);
const staticDef = R.incumbentDefence(world.seed, x, y, ageDays);
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
const site = { x, y, type: 'incumbent' };
const uid = U.userOfOperator(db, attackerOp.id);
if (mv.type === 'scan') {
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
const res = R.resolveScan(sa, D.INCUMBENT.scanStrength);
const loss = R.applyLoss(mv.units, res.lossFraction);
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, attackerOp.id);
const intel = res.success ? { defence: staticDef, bonusAvailable: !taken, hardwareBonus: D.INCUMBENT.hardwareBonus } : null;
createReport(ctx, {
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site },
data: { success: res.success, detail: res.detail, site, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
recipients: [{ userId: uid, role: 'attacker' }],
});
sendHome(ctx, mv, loss.survivors, {});
return;
}
const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef });
const survivors = Object.assign({}, b.attacker.survivors);
let bonus = null;
const cargo = {};
if (b.attackerWins) {
const first = db.run('INSERT OR IGNORE INTO incumbent_takes (world_id, x, y, operator_id, taken_at) VALUES (?, ?, ?, ?, ?)', world.id, x, y, attackerOp.id, now);
if (first.changes) {
cargo.hardware = D.INCUMBENT.hardwareBonus;
bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) };
}
}
const ret = sendHome(ctx, mv, survivors, cargo);
createReport(ctx, {
worldId: mv.worldId, type: 'incumbent', now,
summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus },
data: {
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site, origin: townBrief(origin),
attacker: { operator: opBrief(attackerOp), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
power: { attack: b.A, defence: b.D }, bonus, returnMovementId: ret ? ret.id : null,
},
recipients: [{ userId: uid, role: 'attacker' }],
});
}
// A takeover completed: the POP changes owner. Pending work of the old owner stops, reinforcements of the old owner
// standing elsewhere are re-homed, the new owner starts at conqueredLoyalty.
function transferTown(ctx, town, newOp, oldOp, now) {
const { db } = ctx;
db.run('UPDATE towns SET owner_id = ?, is_capital = 0, loyalty = ?, loyalty_at = ? WHERE id = ?', newOp.id, D.EXPANSION.conqueredLoyalty, now, town.id);
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type IN ('trainDone', 'researchDone') AND status = 'pending'", now, town.id);
db.run("UPDATE events SET payload = json_set(payload, '$.userId', ?) WHERE town_id = ? AND type = 'buildDone' AND status = 'pending'", U.userOfOperator(db, newOp.id), town.id);
// units of the old owner that were hosted here (should be dead already) or that belonged to this POP and stand elsewhere
const home = U.homeTownFor(db, oldOp.id);
for (const g of U.awayGroups(db, town.id)) {
db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', g.hostTownId, town.id);
if (!home) continue;
if (home.id === g.hostTownId) U.addHome(db, home.id, g.units); else U.addStationed(db, g.hostTownId, home.id, g.units);
}
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
const oldUser = U.userOfOperator(db, oldOp.id), newUser = U.userOfOperator(db, newOp.id);
if (oldUser) ctx.notify(oldUser, town.worldId, 'town_lost', { townId: town.id, name: town.name, by: opBrief(newOp) });
if (newUser) ctx.notify(newUser, town.worldId, 'town_gained', { townId: town.id, name: town.name });
}
module.exports = { arrive, defenderGroups, transferTown };

8
server/military/ctx.js Normal file
View file

@ -0,0 +1,8 @@
'use strict';
/* Commands get { db, clock, now, scheduler }, events additionally { enqueue, notify }. Military code uses the event shape
* everywhere, so command entry points call `ctxOf(ctx)` first (idempotent). */
module.exports = function ctxOf(ctx) {
if (ctx.enqueue && ctx.notify) return ctx;
const s = ctx.scheduler;
return Object.assign({}, ctx, { enqueue: (e) => s.enqueue(e), notify: (u, w, t, p) => s.notify(u, w, t, p) });
};

View file

@ -0,0 +1,58 @@
'use strict';
/*
* Movement rows: creating them (together with their arrive/return event), reading them, return legs.
* A movement is `out` until its event runs; a recall turns it into `recalled` and creates a return movement.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const j = (s) => JSON.parse(s || '{}');
function fromRow(r) {
if (!r) return null;
return {
id: r.id, worldId: r.world_id, ownerId: r.owner_id, type: r.type, fromTownId: r.from_town_id, toTownId: r.to_town_id,
from: { x: r.from_x, y: r.from_y }, to: { x: r.to_x, y: r.to_y }, units: j(r.units), cargo: j(r.cargo),
departAt: r.depart_at, arriveAt: r.arrive_at, status: r.status, eventId: r.event_id, parentId: r.parent_id, extra: j(r.extra),
};
}
function getMovement(db, id) { return fromRow(db.get('SELECT * FROM movements WHERE id = ?', id)); }
// Insert a movement and the event that will resolve it ('arrive' for everything but returns, 'return' for returns).
// o: { worldId, ownerId, type, fromTownId, toTownId, from:{x,y}, to:{x,y}, units, cargo, departAt, arriveAt, parentId, extra }
function insertMovement(ctx, o) {
const { db } = ctx;
const r = db.run(`INSERT INTO movements (world_id, owner_id, type, from_town_id, to_town_id, from_x, from_y, to_x, to_y, units, cargo,
depart_at, arrive_at, status, parent_id, extra, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'out', ?, ?, ?)`,
o.worldId, o.ownerId, o.type, o.fromTownId || null, o.toTownId || null, o.from.x, o.from.y, o.to.x, o.to.y,
JSON.stringify(o.units || {}), JSON.stringify(o.cargo || {}), o.departAt, Math.round(o.arriveAt), o.parentId || null, JSON.stringify(o.extra || {}), ctx.now);
const id = Number(r.lastInsertRowid);
const eventId = ctx.enqueue({ worldId: o.worldId, dueAt: o.arriveAt, type: o.type === 'return' ? 'return' : 'arrive', townId: o.toTownId || null, payload: { movementId: id } });
db.run('UPDATE movements SET event_id = ? WHERE id = ?', eventId, id);
return getMovement(db, id);
}
// Units (and cargo) heading home from where they are. `fromTown` may be null (an incumbent site or an empty tile);
// `at` = where they are ({x,y}); `to` = the destination POP row. arriveAt defaults to now + travel time.
function launchReturn(ctx, o) {
const to = o.to;
const dist = R.distance(o.at.x, o.at.y, to.x, to.y);
const world = ctx.db.get('SELECT speed FROM worlds WHERE id = ?', o.worldId);
const arriveAt = o.arriveAt !== undefined ? o.arriveAt : ctx.now + R.movementMs(dist, o.units, world.speed);
return insertMovement(ctx, {
worldId: o.worldId, ownerId: o.ownerId, type: 'return', fromTownId: o.fromTownId || null, toTownId: to.id,
from: o.at, to: { x: to.x, y: to.y }, units: o.units, cargo: o.cargo, departAt: ctx.now, arriveAt, parentId: o.parentId, extra: o.extra,
});
}
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports.
function activeLinks(db, townId) {
return db.get(`SELECT COUNT(*) AS n FROM movements WHERE status = 'out' AND
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n;
}
// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }).
const hooks = { transportArrived: [] };
module.exports = { fromRow, getMovement, insertMovement, launchReturn, activeLinks, hooks };

109
server/military/power.js Normal file
View file

@ -0,0 +1,109 @@
'use strict';
/*
* Unit power: while the battery is empty and net power is negative, the units in a POP are offline (no attack or
* defence value, cannot move). After MILITARY.decommissionHours (divided by world speed) offline, the most expensive
* units are decommissioned until the draw fits the output again.
*
* Whether units are online right now is always computed from the lazy battery value (`online`), so reads and combat
* never depend on an event having run. The `powerCheck` event exists for the side effects: the "units offline"
* notification and the decommission. `reschedule` is idempotent: it cancels the pending check of the POP and enqueues
* the one that is correct for the current rates. Call it after ANYTHING that changes unit draw or building levels of a
* POP (units arriving or leaving, losses, buildings finishing or being damaged).
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { loadTown, settle } = require('../state');
const U = require('./units');
const EPS = D.MILITARY.batteryEpsilon;
// Are the units in this town online at `now`? (the town object may be unsettled: resourcesAt projects it)
function online(town, now) {
const c = R.resourcesAt(town, now);
return !(c.amounts.battery <= EPS && c.rates.powerNet < 0);
}
// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }.
function drawingUnits(db, townId) {
const out = U.homeUnits(db, townId);
for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units);
return out;
}
function reschedule(ctx, townId, now) {
const { db } = ctx;
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type = 'powerCheck' AND status = 'pending'", now, townId);
const town = loadTown(db, townId);
if (!town) return;
if (!(town.unitDraw > 0)) { db.run('DELETE FROM town_power WHERE town_id = ?', townId); return; }
if (online(town, now)) {
db.run('DELETE FROM town_power WHERE town_id = ?', townId);
const at = R.batteryEmptyAt(town, now);
if (at !== null) ctx.enqueue({ worldId: town.worldId, dueAt: at + 1, type: 'powerCheck', townId, payload: { townId } });
return;
}
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', townId);
if (!row || row.offline_since === null) {
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', townId, now);
row = { offline_since: now };
}
ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } });
}
// Decommission the most expensive units (home first, then reinforcements) until the draw fits. The town is settled.
function decommission(ctx, town, now) {
const { db } = ctx;
const units = drawingUnits(db, town.id);
const rates = R.ratesPerHour(Object.assign({}, town, { unitDraw: 0 }));
const plan = R.decommissionPlan(units, rates.powerOut - rates.powerDraw);
const removed = {};
const byOwner = new Map(); // userId -> { unit: n }, who lost units
const note = (userId, unit, n) => { if (!byOwner.has(userId)) byOwner.set(userId, {}); const o = byOwner.get(userId); o[unit] = (o[unit] || 0) + n; };
const ownerUser = U.userOfOperator(db, town.ownerId);
for (const unit of Object.keys(plan)) {
let left = plan[unit];
const home = U.homeUnits(db, town.id)[unit] || 0;
const fromHome = Math.min(home, left);
if (fromHome > 0) { U.setHomeUnit(db, town.id, unit, home - fromHome); left -= fromHome; note(ownerUser, unit, fromHome); }
for (const g of U.hostedGroups(db, town.id)) {
if (left <= 0) break;
const have = g.units[unit] || 0;
const n = Math.min(have, left);
if (n > 0) {
U.setStationed(db, town.id, g.ownerTownId, unit, have - n); left -= n;
const ot = db.get('SELECT t.owner_id AS oid FROM towns t WHERE t.id = ?', g.ownerTownId);
note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n);
}
}
removed[unit] = plan[unit] - left;
}
for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost });
return removed;
}
// Event handler: payload { townId }. Settles the POP to the due time and acts on what it finds.
function powerCheck(ctx, ev) {
const { db } = ctx;
const town = loadTown(db, ev.townId);
if (!town) return;
settle(db, town, ev.dueAt);
if (town.unitDraw > 0 && !online(town, ev.dueAt)) {
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', town.id);
if (!row || row.offline_since === null) {
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', town.id, ev.dueAt);
row = { offline_since: ev.dueAt };
const uid = U.userOfOperator(db, town.ownerId);
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId: town.id, since: ev.dueAt });
}
if (ev.dueAt >= row.offline_since + R.decommissionMs(town.speed)) {
const removed = decommission(ctx, town, ev.dueAt);
if (!Object.keys(removed).some((k) => removed[k] > 0)) { // rounding noise, nothing to remove: stand down, never loop
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
return;
}
}
}
reschedule(ctx, town.id, ev.dueAt);
}
module.exports = { online, drawingUnits, reschedule, decommission, powerCheck };

View file

@ -0,0 +1,32 @@
'use strict';
/*
* Reports: one `reports` row shared by every participant (`report_recipients`, with a per-user read flag). Kept
* MILITARY.reportRetentionMs (real time); the `reportCleanup` event deletes expired ones and re-arms itself only while
* reports remain.
*/
const D = require('../../public/js/data.js');
// o: { worldId, type, now, summary, data, recipients: [{ userId, role }] } -> report id
function createReport(ctx, o) {
const { db } = ctx;
const r = db.run('INSERT INTO reports (world_id, type, created_at, expires_at, summary, data) VALUES (?, ?, ?, ?, ?, ?)',
o.worldId, o.type, o.now, o.now + D.MILITARY.reportRetentionMs, JSON.stringify(o.summary || {}), JSON.stringify(o.data || {}));
const id = Number(r.lastInsertRowid);
const seen = new Set();
for (const rc of o.recipients) {
if (!rc.userId || seen.has(rc.userId)) continue;
seen.add(rc.userId);
db.run('INSERT INTO report_recipients (report_id, user_id, role) VALUES (?, ?, ?)', id, rc.userId, rc.role);
ctx.notify(rc.userId, o.worldId, 'report', { reportId: id, type: o.type, role: rc.role });
}
ensureCleanup(ctx, o.worldId, o.now);
return id;
}
function ensureCleanup(ctx, worldId, now) {
const { db } = ctx;
const pending = db.get("SELECT 1 AS x FROM events WHERE type = 'reportCleanup' AND world_id = ? AND status = 'pending' LIMIT 1", worldId);
if (!pending) ctx.enqueue({ worldId, dueAt: now + D.MILITARY.reportRetentionMs, type: 'reportCleanup', payload: { worldId } });
}
module.exports = { createReport, ensureCleanup };

153
server/military/units.js Normal file
View file

@ -0,0 +1,153 @@
'use strict';
/*
* Data helpers for units, reinforcements, research and operators, shared by the military commands, events and views.
* Units are always { unitId: count }. Always settle() a town before changing its units: unit power draw is part of its
* rates (state.unitDraw reads town_units and stationed).
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { loadTown } = require('../state');
function homeUnits(db, townId) {
const out = {};
for (const r of db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) out[r.unit] = r.count;
return out;
}
function setHomeUnit(db, townId, unit, count) {
if (count > 0) db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, unit, count);
else db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', townId, unit);
}
function addHome(db, townId, units) {
const cur = homeUnits(db, townId);
for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, (cur[k] || 0) + units[k]);
}
// Removes `units` from home; throws not_enough_units when the town does not have them (callers check first).
function removeHome(db, townId, units) {
const cur = homeUnits(db, townId);
for (const k of Object.keys(units || {})) {
if (!(units[k] > 0)) continue;
if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
}
for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, cur[k] - units[k]);
}
// Reinforcements standing in a host town: [{ ownerTownId, units }] grouped by the POP they belong to.
function hostedGroups(db, hostTownId) {
const by = new Map();
for (const r of db.all('SELECT owner_town_id, unit, count FROM stationed WHERE host_town_id = ? ORDER BY owner_town_id, unit', hostTownId)) {
if (!by.has(r.owner_town_id)) by.set(r.owner_town_id, {});
by.get(r.owner_town_id)[r.unit] = r.count;
}
return Array.from(by, ([ownerTownId, units]) => ({ ownerTownId, units }));
}
// Units of owner_town_id's operator standing in other POPs: [{ hostTownId, units }].
function awayGroups(db, ownerTownId) {
const by = new Map();
for (const r of db.all('SELECT host_town_id, unit, count FROM stationed WHERE owner_town_id = ? ORDER BY host_town_id, unit', ownerTownId)) {
if (!by.has(r.host_town_id)) by.set(r.host_town_id, {});
by.get(r.host_town_id)[r.unit] = r.count;
}
return Array.from(by, ([hostTownId, units]) => ({ hostTownId, units }));
}
function stationedOf(db, hostTownId, ownerTownId) {
const out = {};
for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', hostTownId, ownerTownId)) out[r.unit] = r.count;
return out;
}
function setStationed(db, hostTownId, ownerTownId, unit, count) {
if (count > 0) db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (host_town_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', hostTownId, ownerTownId, unit, count);
else db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ? AND unit = ?', hostTownId, ownerTownId, unit);
}
function addStationed(db, hostTownId, ownerTownId, units) {
const cur = stationedOf(db, hostTownId, ownerTownId);
for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, (cur[k] || 0) + units[k]);
}
function removeStationed(db, hostTownId, ownerTownId, units) {
const cur = stationedOf(db, hostTownId, ownerTownId);
for (const k of Object.keys(units || {})) {
if (!(units[k] > 0)) continue;
if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
}
for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, cur[k] - units[k]);
}
// Research levels of a POP as { 'unit:stat': level }.
function researchLevels(db, townId) {
const out = {};
for (const r of db.all('SELECT unit, stat, level FROM town_research WHERE town_id = ?', townId)) out[R.researchKey(r.unit, r.stat)] = r.level;
return out;
}
// Snapshot of the research of `townId` for the unit types in `units` (stored on a movement at departure).
function researchSnapshot(db, townId, units) {
const all = researchLevels(db, townId);
const out = {};
for (const u of Object.keys(units)) for (const stat of D.RESEARCH.stats) { const k = R.researchKey(u, stat); if (all[k]) out[k] = all[k]; }
return out;
}
// Validates and normalises the `units` object of a request: known ids, whole numbers >= 0, zeros dropped.
function cleanUnits(raw) {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new GameError('validation_failed', { errors: [{ path: 'units', message: 'must be an object' }] });
const out = {};
for (const k of Object.keys(raw)) {
if (!R.unitDef(k)) throw new GameError('unknown_unit', { unit: k });
const n = raw[k];
if (!Number.isInteger(n) || n < 0 || n > 1e7) throw new GameError('validation_failed', { errors: [{ path: 'units.' + k, message: 'must be a whole number >= 0' }] });
if (n > 0) out[k] = n;
}
return out;
}
const sumInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; };
const isEmpty = (units) => !Object.keys(units || {}).some((k) => units[k] > 0);
// ---- operators
function getOperator(db, id) { return db.get('SELECT * FROM operators WHERE id = ?', id); }
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
function operatorTowns(db, operatorId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY id', operatorId); }
// Footprint over all POPs of the operator at `now` (each POP's footprint keeps growing from its buildings).
function operatorFootprint(db, operatorId, now) {
let sum = 0;
for (const t of operatorTowns(db, operatorId)) sum += R.footprintAt(loadTown(db, t.id), now);
return sum;
}
function incumbentTakes(db, operatorId) { return db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', operatorId).n; }
function researchBonusOf(db, operatorId) { return R.researchSpeedBonus(incumbentTakes(db, operatorId)); }
// Where do units of `operatorId` go when their origin POP is gone: the capital, else the oldest POP; null if none.
function homeTownFor(db, operatorId, preferTownId) {
if (preferTownId) {
const t = db.get('SELECT * FROM towns WHERE id = ? AND owner_id = ?', preferTownId, operatorId);
if (t) return t;
}
return db.get('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id LIMIT 1', operatorId) || null;
}
// May `fromOp` stand units in a POP of `toOp`? Own POPs, same alliance, confederation.
function mayReinforce(db, fromOp, toOp) {
if (fromOp === toOp) return true;
return require('../alliances').confederated(db, fromOp, toOp);
}
// Pacts (same alliance, NAP, confederation) forbid hostile movements between the partners.
function pactBlocks(db, fromOp, toOp) {
if (fromOp === toOp) return false;
return require('../alliances').pactPartners(db, fromOp, toOp);
}
module.exports = {
homeUnits, setHomeUnit, addHome, removeHome, hostedGroups, awayGroups, stationedOf, setStationed, addStationed, removeStationed,
researchLevels, researchSnapshot, cleanUnits, sumInto, isEmpty,
getOperator, userOfOperator, operatorTowns, operatorFootprint, incumbentTakes, researchBonusOf, homeTownFor, mayReinforce, pactBlocks,
};

155
server/military/views.js Normal file
View file

@ -0,0 +1,155 @@
'use strict';
/*
* Read models for the military stage: the military part of GET /towns/:id, the movements list with incoming warnings,
* reports, and tile info for the send dialog. Reads catch the event queue up first (via `fresh`) and never write.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { loadWorld } = require('../state');
const U = require('./units');
const P = require('./power');
const j = (s) => JSON.parse(s || '{}');
function townNames(db, ids) {
const out = new Map();
for (const id of ids) {
if (!id || out.has(id)) continue;
const t = db.get('SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?', id);
out.set(id, t ? { id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital, owner: { id: t.oid, name: t.oname, asNumber: t.asn } } : null);
}
return out;
}
// What the owner of a movement sees.
function ownerView(m, names) {
const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null;
const extra = j(m.extra);
return {
id: m.id, type: m.type, status: m.status, ownerId: m.owner_id,
from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null },
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
units: j(m.units), cargo: j(m.cargo), departAt: m.depart_at, arriveAt: m.arrive_at,
recallableUntil: m.type === 'return' ? null : m.depart_at + D.MILITARY.recallWindowMs,
target: extra.target || null, parentId: m.parent_id,
};
}
// What the target of somebody else's movement sees: origin and ETA, never the type, units or cargo.
function incomingView(m, names) {
const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null;
return {
id: m.id, type: 'unknown', status: m.status, incoming: true,
from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null, owner: f ? f.owner : null },
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
departAt: m.depart_at, arriveAt: m.arrive_at,
};
}
// Active movements: the operator's own (outgoing legs, returns, transports) and other operators' movements heading for
// the operator's POPs. `townId` limits both to one POP.
function movementLists(db, operatorId, townId) {
const own = db.all(`SELECT * FROM movements WHERE owner_id = ? AND status = 'out' ${townId ? 'AND (from_town_id = ? OR to_town_id = ?)' : ''} ORDER BY arrive_at, id LIMIT ?`,
...(townId ? [operatorId, townId, townId, D.MILITARY.maxLists] : [operatorId, D.MILITARY.maxLists]));
const inc = db.all(`SELECT m.* FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id = ? AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return'
${townId ? 'AND m.to_town_id = ?' : ''} ORDER BY m.arrive_at, m.id LIMIT ?`,
...(townId ? [operatorId, operatorId, townId, D.MILITARY.maxLists] : [operatorId, operatorId, D.MILITARY.maxLists]));
const names = townNames(db, own.concat(inc).flatMap((m) => [m.from_town_id, m.to_town_id]));
return { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
}
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
function townMilitary(db, t, now, world) {
const home = U.homeUnits(db, t.id);
const online = P.online(t, now);
const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId)));
const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units }));
const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units }));
const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id)
.map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; });
const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id);
const rp = rq ? JSON.parse(rq.payload) : null;
const bonus = U.researchBonusOf(db, t.ownerId);
const trainable = D.UNIT_ORDER.map((unit) => {
const def = D.UNITS[unit];
const missing = R.unitMissing(t, unit);
return { unit, building: def.building, role: def.role, cost: R.unitCost(unit, 1), timeMs: R.trainTimeMs(unit, 1, t.buildings[def.building] ? t.buildings[def.building].level : 0, world.speed), missing, locked: missing.length > 0 };
});
const offline = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', t.id);
const op = U.getOperator(db, t.ownerId);
const links = R.transportLinks(t);
return {
units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away },
training, trainable,
research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel },
transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: D.TRANSPORT.capacityPerLink },
movements: movementLists(db, t.ownerId, t.id),
protectionUntil: op.protection_until,
};
}
function createMilitaryQueries({ db, clock, scheduler }) {
const fresh = () => { scheduler.runDue(); return clock.now(); };
function operatorFor(userId, worldId) {
const op = worldId ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
if (!op) throw new GameError('not_found', { what: 'operator' });
return op;
}
function movements(userId, { worldId }) {
const now = fresh();
const op = operatorFor(userId, worldId);
return Object.assign({ serverTime: now }, movementLists(db, op.id, null));
}
function reports(userId, { after, limit, unread }) {
const now = fresh();
const n = limit || 25;
const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id
WHERE rr.user_id = ? ${after ? 'AND r.id < ?' : ''} ${unread ? 'AND rr.read_at IS NULL' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [userId, after, n + 1] : [userId, n + 1]));
const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, role: r.role, read: r.read_at !== null, summary: j(r.summary) }));
const unreadCount = db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NULL', userId).n;
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null, unread: unreadCount };
}
function report(userId, id) {
const now = fresh();
const r = db.get(`SELECT r.*, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? AND r.id = ?`, userId, id);
if (!r) throw new GameError('not_found', { what: 'report' });
return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, role: r.role, read: r.read_at !== null, summary: j(r.summary), data: j(r.data) } };
}
// Public information about a tile, for the send dialog: what is there, who owns it, how far it is from each of my POPs,
// whether I could found a POP there.
function tileInfo(userId, { worldId, x, y }) {
const now = fresh();
const op = operatorFor(userId, worldId);
const world = loadWorld(db, op.world_id);
const tile = R.tileAt(world.seed, world.map_radius, x, y);
if (tile.type === 'void') throw new GameError('not_found', { what: 'tile' });
const row = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
const mine = U.operatorTowns(db, op.id);
const out = { serverTime: now, x, y, type: row ? 'pop' : tile.type, bonus: tile.bonus || null, distances: mine.map((t) => ({ townId: t.id, distance: R.distance(t.x, t.y, x, y) })) };
if (row) {
const o = U.getOperator(db, row.owner_id);
out.town = { id: row.id, name: row.name, isCapital: !!row.is_capital, owner: { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protected: R.isProtected(o.protection_until, now), protectionUntil: o.protection_until }, mine: o.id === op.id };
}
if (tile.type === 'incumbent') {
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, op.id);
out.incumbent = { takenByYou: taken, hardwareBonus: taken ? 0 : D.INCUMBENT.hardwareBonus };
}
const fp = U.operatorFootprint(db, op.id, now);
const gate = R.footprintGate(mine.length, fp);
let nearest = Infinity;
for (const t of mine) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
const sc = R.settleCheck({ tileType: tile.type, occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp });
out.settle = { possible: sc.ok, code: sc.ok ? null : sc.code, footprint: fp, footprintNeeded: gate.need, maxDistance: D.EXPANSION.maxDistance };
return out;
}
return { movements, reports, report, tileInfo };
}
module.exports = { townMilitary, movementLists, createMilitaryQueries };

View file

@ -7,6 +7,7 @@ const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { GameError } = require('./errors');
const { loadWorld, townFromRow, pendingBuilds } = require('./state');
const { allianceBrief } = require('./alliances');
function createQueries({ db, clock, scheduler }) {
const fresh = () => { scheduler.runDue(); return clock.now(); };
@ -23,7 +24,7 @@ function createQueries({ db, clock, scheduler }) {
const world = loadWorld(db, o.world_id);
const towns = db.all('SELECT id, name, x, y, is_capital FROM towns WHERE owner_id = ? ORDER BY id', o.id)
.map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital }));
return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protectionUntil: o.protection_until, world: worldView(world), towns };
return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, alliance: allianceBrief(db, o.alliance_id), protectionUntil: o.protection_until, world: worldView(world), towns };
});
return { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators };
}
@ -68,6 +69,7 @@ function createQueries({ db, clock, scheduler }) {
loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t),
resources, power, buildings, queue, queueSlots: R.queueSlots(t),
bonus: t.bonus,
military: require('./military/views').townMilitary(db, t, now, world),
},
};
}
@ -93,11 +95,11 @@ function createQueries({ db, clock, scheduler }) {
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
}
}
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, o.protection_until AS prot
FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`,
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, a.tag AS atag, a.name AS aname, o.protection_until AS prot
FROM towns t JOIN operators o ON o.id = t.owner_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`,
world.id, x0, x1, y0, y1).map((t) => ({
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital,
owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, protected: t.prot > now },
owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, alliance: t.ally ? { id: t.ally, tag: t.atag, name: t.aname } : null, protected: t.prot > now },
}));
return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns };
}

140
server/routes/alliances.js Normal file
View file

@ -0,0 +1,140 @@
'use strict';
/* Alliances, invites, pinned notes and diplomacy (stage 5). Fixed paths are registered before /alliances/:id. */
const { reply } = require('../http');
const { GameError } = require('../errors');
const { createSocialQueries } = require('../socialQueries');
const D = require('../../public/js/data.js');
const S = D.SOCIAL;
const int1 = { type: 'integer', minimum: 1 };
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
const worldQ = { worldId: int1 };
function register(router, services) {
const { commands } = services;
const social = createSocialQueries(services);
const run = (name, args) => commands.run(name, args);
const base = ['unauthorized', 'not_found', 'validation_failed'];
const roleErrs = base.concat(['forbidden']);
router.get('/alliances/mine', {
summary: 'Your alliance, role and permissions (null alliance when you are not in one)', tag: 'alliances',
query: { type: 'object', properties: worldQ }, response: { $ref: 'AllianceMine' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
}, ({ user, query }) => social.mine(user.id, query.worldId));
router.get('/alliances', {
summary: 'Alliance directory of a world, optional name/tag search (cursor: after = last id)', tag: 'alliances',
query: { type: 'object', properties: Object.assign({ q: { type: 'string', maxLength: 40 } }, page, worldQ) }, response: { $ref: 'AllianceList' }, errors: base,
}, ({ user, query }) => social.list(user.id, query));
router.post('/alliances', {
summary: 'Found an alliance (needs Peering office 1+); you become its leader', tag: 'alliances', status: 201,
body: { type: 'object', required: ['name', 'tag'], properties: { name: { type: 'string', minLength: S.nameLen[0], maxLength: S.nameLen[1] * 2 }, tag: { type: 'string', minLength: S.tagLen[0], maxLength: S.tagLen[1] }, worldId: int1 } },
response: { $ref: 'AllianceCreated' }, errors: base.concat(['peering_office_required', 'already_in_alliance', 'alliance_name_taken', 'alliance_tag_taken']),
}, ({ user, body }) => reply(201, run('allianceCreate', { userId: user.id, worldId: body.worldId, name: body.name, tag: body.tag })));
router.get('/alliance-invites', {
summary: 'Open invites addressed to you', tag: 'alliances', response: { $ref: 'ReceivedInviteList' }, errors: ['unauthorized'],
}, ({ user }) => social.invitesReceived(user.id));
const answerErrs = ['unauthorized', 'not_found', 'conflict', 'invite_expired', 'already_in_alliance', 'peering_office_required', 'alliance_full'];
router.post('/alliance-invites/:id/accept', {
summary: 'Accept an invite (needs Peering office 1+ and no alliance yet)', tag: 'alliances', response: { $ref: 'Changed' }, errors: answerErrs,
}, ({ user, params }) => run('allianceInviteAnswer', { userId: user.id, inviteId: params.id, accept: true }));
router.post('/alliance-invites/:id/decline', {
summary: 'Decline an invite', tag: 'alliances', response: { $ref: 'Changed' }, errors: answerErrs,
}, ({ user, params }) => run('allianceInviteAnswer', { userId: user.id, inviteId: params.id, accept: false }));
router.get('/alliances/:id', {
summary: 'Public alliance profile: size, leader, footprint, your role and relation to it', tag: 'alliances', response: { $ref: 'AllianceDetail' }, errors: ['unauthorized', 'not_found'],
}, ({ user, params }) => social.get(user.id, params.id));
router.get('/alliances/:id/members', {
summary: 'Member list with role, POP count, footprint and last online (members only)', tag: 'alliances', response: { $ref: 'AllianceMemberList' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => social.members(user.id, params.id));
router.get('/alliances/:id/invites', {
summary: 'Pending invites sent by this alliance (needs viewInvites)', tag: 'alliances', response: { $ref: 'AllianceInviteList' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => social.invitesSent(user.id, params.id));
router.post('/alliances/:id/invite', {
summary: 'Invite an operator by id or name (needs invite). Repeating it returns the pending invite', tag: 'alliances', status: 201,
body: { type: 'object', properties: { operatorId: int1, name: { type: 'string', minLength: 1, maxLength: 40 } } },
response: { $ref: 'InviteResult' }, errors: roleErrs.concat(['already_in_alliance', 'alliance_full', 'conflict']),
}, ({ user, params, body }) => {
if ((body.operatorId === undefined) === (body.name === undefined)) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'give exactly one of operatorId, name' }] });
const r = run('allianceInvite', { userId: user.id, allianceId: params.id, operatorId: body.operatorId, name: body.name });
return reply(r.changed ? 201 : 200, r);
});
router.del('/alliances/:id/invites/:inviteId', {
summary: 'Cancel a pending invite (needs cancelInvite)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden', 'conflict'],
}, ({ user, params }) => run('allianceInviteCancel', { userId: user.id, allianceId: params.id, inviteId: params.inviteId }));
router.post('/alliances/:id/leave', {
summary: 'Leave the alliance. The leader must transfer first unless alone (then it is disbanded)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'leader_must_transfer'],
}, ({ user, params }) => run('allianceLeave', { userId: user.id, allianceId: params.id }));
router.post('/alliances/:id/kick', {
summary: 'Remove a member you outrank (needs kick)', tag: 'alliances', body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } },
response: { $ref: 'Changed' }, errors: roleErrs,
}, ({ user, params, body }) => run('allianceKick', { userId: user.id, allianceId: params.id, operatorId: body.operatorId }));
router.post('/alliances/:id/role', {
summary: 'Set a member role: diplomat, officer or member (leader only)', tag: 'alliances',
body: { type: 'object', required: ['operatorId', 'role'], properties: { operatorId: int1, role: { type: 'string', enum: ['diplomat', 'officer', 'member'] } } },
response: { $ref: 'Changed' }, errors: roleErrs,
}, ({ user, params, body }) => run('allianceRole', { userId: user.id, allianceId: params.id, operatorId: body.operatorId, role: body.role }));
router.post('/alliances/:id/transfer', {
summary: 'Hand leadership to another member; you become an officer (leader only)', tag: 'alliances',
body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, response: { $ref: 'Changed' }, errors: roleErrs,
}, ({ user, params, body }) => run('allianceTransfer', { userId: user.id, allianceId: params.id, operatorId: body.operatorId }));
router.post('/alliances/:id/disband', {
summary: 'Disband the alliance (leader only)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => run('allianceDisband', { userId: user.id, allianceId: params.id }));
// ---- pinned notes
const noteBody = { type: 'object', required: ['text'], properties: { text: { type: 'string', minLength: 1, maxLength: S.noteMax } } };
router.get('/alliances/:id/notes', {
summary: 'Pinned notes (members only)', tag: 'alliances', response: { $ref: 'AllianceNoteList' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => social.notes(user.id, params.id));
router.post('/alliances/:id/notes', {
summary: 'Pin a note (needs editNotes)', tag: 'alliances', status: 201, body: noteBody, response: { $ref: 'AllianceNoteResponse' }, errors: roleErrs.concat(['notes_full']),
}, ({ user, params, body }) => reply(201, run('allianceNoteAdd', { userId: user.id, allianceId: params.id, text: body.text })));
router.post('/alliances/:id/notes/:noteId', {
summary: 'Edit a pinned note (needs editNotes)', tag: 'alliances', body: noteBody, response: { $ref: 'AllianceNoteResponse' }, errors: roleErrs,
}, ({ user, params, body }) => run('allianceNoteEdit', { userId: user.id, allianceId: params.id, noteId: params.noteId, text: body.text }));
router.del('/alliances/:id/notes/:noteId', {
summary: 'Remove a pinned note (needs editNotes)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => run('allianceNoteDelete', { userId: user.id, allianceId: params.id, noteId: params.noteId }));
// ---- diplomacy
router.get('/alliances/:id/diplomacy', {
summary: 'Relations with other alliances (with scheduled changes) and open proposals (members only)', tag: 'diplomacy', response: { $ref: 'Diplomacy' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => social.diplomacy(user.id, params.id));
router.post('/alliances/:id/diplomacy', {
summary: 'Change the relation to another alliance (needs diplomacy): war applies at once from neutral, pacts need acceptance, cancelling a pact takes 24 h / world speed', tag: 'diplomacy',
body: { type: 'object', required: ['targetId', 'state'], properties: { targetId: int1, state: { type: 'string', enum: S.diplomacyStates } } },
response: { $ref: 'DiplomacyResult' }, errors: roleErrs.concat(['diplomacy_invalid', 'diplomacy_pending', 'proposal_exists']),
}, ({ user, params, body }) => run('diploPropose', { userId: user.id, allianceId: params.id, targetId: body.targetId, state: body.state }));
router.del('/alliances/:id/diplomacy/:otherId/pending', {
summary: 'Take back a scheduled cancel before it takes effect (the alliance that started it, needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'],
}, ({ user, params }) => run('diploRevoke', { userId: user.id, allianceId: params.id, otherId: params.otherId }));
const propErrs = ['unauthorized', 'not_found', 'forbidden', 'conflict', 'proposal_expired', 'diplomacy_invalid', 'diplomacy_pending'];
router.post('/diplomacy/proposals/:proposalId/accept', {
summary: 'Accept a diplomatic proposal addressed to your alliance (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: propErrs,
}, ({ user, params }) => run('diploAnswer', { userId: user.id, proposalId: params.proposalId, accept: true }));
router.post('/diplomacy/proposals/:proposalId/decline', {
summary: 'Decline a diplomatic proposal addressed to your alliance (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: propErrs,
}, ({ user, params }) => run('diploAnswer', { userId: user.id, proposalId: params.proposalId, accept: false }));
router.del('/diplomacy/proposals/:proposalId', {
summary: 'Withdraw a proposal your alliance made (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden', 'conflict'],
}, ({ user, params }) => run('diploWithdraw', { userId: user.id, proposalId: params.proposalId }));
}
module.exports = { register };

View file

@ -1,6 +1,6 @@
'use strict';
/* Registers every REST route. One file per resource; each exports register(router, services). */
const files = [require('./auth'), require('./me'), require('./towns'), require('./map')];
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports')];
function register(router, services) {
for (const f of files) f.register(router, services);

71
server/routes/messages.js Normal file
View file

@ -0,0 +1,71 @@
'use strict';
/* Player messages and alliance broadcasts (stage 5). Fixed paths first, /messages/:id last. */
const { reply } = require('../http');
const { createSocialQueries } = require('../socialQueries');
const D = require('../../public/js/data.js');
const int1 = { type: 'integer', minimum: 1 };
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
const listQuery = (extra) => ({ type: 'object', properties: Object.assign({}, page, { worldId: int1 }, extra || {}) });
function register(router, services) {
const { commands } = services;
const social = createSocialQueries(services);
const run = (name, args) => commands.run(name, args);
router.get('/messages/inbox', {
summary: 'Received messages, newest first (cursor: after = last id of the previous page); `unread` counts all unread', tag: 'messages',
query: listQuery({ unread: { type: 'boolean' } }), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
}, ({ user, query }) => social.inbox(user.id, query));
router.get('/messages/outbox', {
summary: 'Sent messages, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
}, ({ user, query }) => social.outbox(user.id, query));
router.get('/messages/alliance', {
summary: 'Broadcasts of your alliance, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'not_in_alliance', 'validation_failed'],
}, ({ user, query }) => social.allianceFeed(user.id, query));
router.get('/messages/thread/:operatorId', {
summary: 'The conversation with one operator, both directions, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
}, ({ user, params, query }) => social.thread(user.id, params.operatorId, query));
router.get('/messages/blocks', {
summary: 'Operators you blocked', tag: 'messages', query: { type: 'object', properties: { worldId: int1 } }, response: { $ref: 'BlockList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
}, ({ user, query }) => social.blocks(user.id, query));
router.post('/messages/blocks', {
summary: 'Block an operator: their messages are no longer delivered to you (they are not told)', tag: 'messages',
body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'validation_failed', 'conflict'],
}, ({ user, body }) => run('messageBlock', { userId: user.id, operatorId: body.operatorId }));
router.del('/messages/blocks/:operatorId', {
summary: 'Unblock an operator', tag: 'messages', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
}, ({ user, params }) => run('messageUnblock', { userId: user.id, operatorId: params.operatorId }));
router.post('/messages/read', {
summary: 'Mark received messages read: a list of ids (max 100) or all', tag: 'messages',
body: { type: 'object', properties: { ids: { type: 'array', maxItems: 100, items: int1 }, all: { type: 'boolean' }, worldId: int1 } },
response: { $ref: 'Changed' }, errors: ['unauthorized', 'validation_failed'],
}, ({ user, body }) => {
const r = commands.run('messageRead', { userId: user.id, ids: body.ids, all: body.all, worldId: body.worldId });
return { changed: r.changed > 0, count: r.changed };
});
router.post('/messages', {
summary: 'Send a message to an operator (toOperatorId or toName) or to your alliance (toAlliance). Plain text, max 2000 characters, rate-limited', tag: 'messages', status: 201,
body: { type: 'object', required: ['text'], properties: {
text: { type: 'string', minLength: 1, maxLength: D.SOCIAL.messageMax }, toOperatorId: int1, toName: { type: 'string', minLength: 1, maxLength: 40 }, toAlliance: { type: 'boolean' }, worldId: int1 } },
response: { $ref: 'MessageSent' }, errors: ['unauthorized', 'not_found', 'validation_failed', 'forbidden', 'not_in_alliance', 'rate_limited'],
}, ({ user, body }) => reply(201, run('messageSend', { userId: user.id, worldId: body.worldId, toOperatorId: body.toOperatorId, toName: body.toName, toAlliance: body.toAlliance, text: body.text })));
router.get('/messages/:id', {
summary: 'One message you sent or received', tag: 'messages', response: { $ref: 'MessageResponse' }, errors: ['unauthorized', 'not_found'],
}, ({ user, params }) => social.message(user.id, params.id));
router.del('/messages/:id', {
summary: 'Delete your own copy of a message (the other side keeps theirs)', tag: 'messages', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found'],
}, ({ user, params }) => run('messageDelete', { userId: user.id, messageId: params.id }));
}
module.exports = { register };

View file

@ -0,0 +1,65 @@
'use strict';
/* Movements: send, recall, list (with incoming warnings), withdraw reinforcements, tile info for the send dialog. */
const { reply } = require('../http');
const { GameError } = require('../errors');
const { createMilitaryQueries } = require('../military/views');
function register(router, services) {
const { commands, db, clock, scheduler } = services;
const mq = createMilitaryQueries({ db, clock, scheduler });
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.post('/movements', {
summary: 'Send units (scan, raid, attack, takeover, reinforce, settle) or resources (transport) from one of your POPs. Target = toTownId or the tile x,y', tag: 'movements',
body: {
type: 'object', required: ['fromTownId', 'type'],
properties: {
fromTownId: { type: 'integer', minimum: 1 },
type: { type: 'string', enum: ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle', 'transport'] },
toTownId: { type: 'integer', minimum: 1 },
x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 },
units: { type: 'object', additionalProperties: true, description: 'unit id -> count' },
cargo: { type: 'object', additionalProperties: true, description: 'transport only: fiber/hardware/capital -> amount' },
target: { type: 'string', maxLength: 32, pattern: '^[a-z0-9_]+$', description: 'exploit kits: the building (f1..f18 or an infrastructure type) to damage on a win' },
wild: { type: 'array', maxItems: 2, items: { type: 'string', maxLength: 32 }, description: 'settle: the two wild slot field types of the new POP' },
confirmEndProtection: { type: 'boolean', description: 'raid/attack/takeover from a protected operator: attacking ends beginner protection' },
},
},
response: { $ref: 'MovementSent' }, status: 201,
errors: errs.concat(['unknown_unit', 'not_enough_units', 'units_offline', 'invalid_target', 'target_protected', 'protection_active', 'out_of_range', 'footprint_too_low',
'cannot_takeover', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources']),
}, ({ user, body }) => {
if (body.type === 'transport') {
if (body.toTownId === undefined) throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'is required for a transport' }] });
return reply(201, commands.run('sendTransport', { userId: user.id, fromTownId: body.fromTownId, toTownId: body.toTownId, cargo: body.cargo }));
}
return reply(201, commands.run('sendMovement', {
userId: user.id, fromTownId: body.fromTownId, type: body.type, toTownId: body.toTownId, x: body.x, y: body.y, units: body.units,
target: body.target, wild: body.wild, confirmEndProtection: body.confirmEndProtection,
}));
});
router.get('/movements', {
summary: 'Your active movements and other operators\' movements heading for your POPs (incoming warnings: origin and ETA only, type hidden)', tag: 'movements',
query: { type: 'object', properties: { worldId: { type: 'integer', minimum: 1 } } },
response: { $ref: 'MovementList' }, errors: errs,
}, ({ user, query }) => mq.movements(user.id, { worldId: query.worldId }));
router.post('/movements/:id/recall', {
summary: 'Turn an outbound movement around within the first 90 seconds', tag: 'movements',
response: { $ref: 'RecallResult' }, errors: errs.concat(['conflict', 'recall_expired']),
}, ({ user, params }) => commands.run('recallMovement', { userId: user.id, movementId: params.id }));
router.post('/towns/:id/withdraw', {
summary: 'Send reinforcements standing in this POP home (host kicks them out, or the units\' owner calls them back)', tag: 'movements',
body: { type: 'object', required: ['ownerTownId'], properties: { ownerTownId: { type: 'integer', minimum: 1 }, units: { type: 'object', additionalProperties: true, description: 'defaults to the whole group' } } },
response: { $ref: 'WithdrawResult' }, errors: errs.concat(['not_enough_units', 'unknown_unit']),
}, ({ user, params, body }) => commands.run('withdrawStationed', { userId: user.id, hostTownId: params.id, ownerTownId: body.ownerTownId, units: body.units }));
router.get('/map/tile', {
summary: 'Public information about one tile for the send dialog: what is there, owner, distance from your POPs, whether you could settle it', tag: 'map',
query: { type: 'object', required: ['x', 'y'], properties: { x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, worldId: { type: 'integer', minimum: 1 } } },
response: { $ref: 'TileInfo' }, errors: errs,
}, ({ user, query }) => mq.tileInfo(user.id, { worldId: query.worldId, x: query.x, y: query.y }));
}
module.exports = { register };

28
server/routes/rankings.js Normal file
View file

@ -0,0 +1,28 @@
'use strict';
/* Rankings (stage 5): operators by footprint, alliances by summed footprint, attackers/defenders by battle points. */
const { createSocialQueries } = require('../socialQueries');
const D = require('../../public/js/data.js');
const q = (extra) => ({ type: 'object', properties: Object.assign({
worldId: { type: 'integer', minimum: 1 }, after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: D.SOCIAL.rankingsPageMax },
}, extra || {}) });
function register(router, services) {
const social = createSocialQueries(services);
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.get('/rankings/operators', {
summary: 'Operators by footprint (cursor: after = number of ranks already seen)', tag: 'rankings', query: q(), response: { $ref: 'RankOperators' }, errors: errs,
}, ({ user, query }) => social.rankOperators(user.id, query));
router.get('/rankings/alliances', {
summary: 'Alliances by summed footprint of their members', tag: 'rankings', query: q(), response: { $ref: 'RankAlliances' }, errors: errs,
}, ({ user, query }) => social.rankAlliances(user.id, query));
router.get('/rankings/battles', {
summary: 'Attackers / defenders by battle points (`by`: attack, defense or total). Empty with available=false until the military stage records points', tag: 'rankings',
query: q({ by: { type: 'string', enum: ['attack', 'defense', 'total'] } }), response: { $ref: 'RankBattles' }, errors: errs,
}, ({ user, query }) => social.rankBattles(user.id, query));
}
module.exports = { register };

26
server/routes/reports.js Normal file
View file

@ -0,0 +1,26 @@
'use strict';
/* Reports of battles, scans, settles and reinforcements (kept 14 days). Newest first; `after` = the last id you have,
* the next page holds older ones. */
const { createMilitaryQueries } = require('../military/views');
function register(router, services) {
const { commands, db, clock, scheduler } = services;
const mq = createMilitaryQueries({ db, clock, scheduler });
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.get('/reports', {
summary: 'Your reports, newest first (cursor: after = id of the last report seen, returns older ones)', tag: 'reports',
query: { type: 'object', properties: { after: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 }, unread: { type: 'boolean' } } },
response: { $ref: 'ReportList' }, errors: errs,
}, ({ user, query }) => mq.reports(user.id, query));
router.post('/reports/read-all', { summary: 'Mark all your reports as read', tag: 'reports', response: { $ref: 'Marked' }, errors: ['unauthorized'] },
({ user }) => commands.run('markReportRead', { userId: user.id, all: true }));
router.get('/reports/:id', { summary: 'One report with its full data', tag: 'reports', response: { $ref: 'ReportResponse' }, errors: errs },
({ user, params }) => mq.report(user.id, params.id));
router.post('/reports/:id/read', { summary: 'Mark a report as read', tag: 'reports', response: { $ref: 'Marked' }, errors: errs },
({ user, params }) => commands.run('markReportRead', { userId: user.id, reportId: params.id }));
}
module.exports = { register };

View file

@ -15,7 +15,7 @@ const schemas = {
Error: obj({ serverTime: int, error: obj({ code: str, message: str, details: { type: 'object', additionalProperties: true } }) }),
World: obj({ id: int, name: str, speed: num, mapRadius: int, seed: int, startAt: int, endAt: { type: ['integer', 'null'] }, status: str, preset: str }),
TownSummary: obj({ id: int, name: str, x: int, y: int, isCapital: bool }),
Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }),
Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }),
Me: obj({ serverTime: int, user: obj({ id: int, username: str, createdAt: int }), operators: arr({ $ref: 'Operator' }) }),
AuthResult: obj({ serverTime: int, token: str, tokenId: int, user: obj({ id: int, username: str }), operators: arr({ $ref: 'Operator' }) }),
Token: obj({ id: int, device: str, createdAt: int, lastUsedAt: int, current: bool }),
@ -31,13 +31,52 @@ const schemas = {
bonus: obj({ fiber: num, hardware: num, capital: num }),
}),
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protected: bool }) }),
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }),
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }),
MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }),
BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }),
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
NotificationList: obj({ serverTime: int, items: arr({ $ref: 'Notification' }), next: { type: ['integer', 'null'] } }),
// ---- stage 5: alliances, diplomacy, messages, rankings
AllianceBrief: obj({ id: int, tag: str, name: str }),
OperatorBrief: obj({ operatorId: int, name: str }),
AllianceInfo: obj({ id: int, worldId: int, name: str, tag: str, sizeCap: int, memberCount: int, leader: { type: ['object', 'null'], additionalProperties: true }, createdAt: int }),
AllianceDetail: obj({ serverTime: int, alliance: { $ref: 'AllianceInfo' } }),
AllianceMine: obj({ serverTime: int, operatorId: int, worldId: int, alliance: { type: ['object', 'null'], additionalProperties: true }, role: { type: ['string', 'null'] }, permissions: arr(str), peeringLevel: int }),
AllianceList: obj({ serverTime: int, items: arr({ $ref: 'AllianceInfo' }), next: { type: ['integer', 'null'] } }),
AllianceMember: obj({ operatorId: int, name: str, asNumber: int, role: str, joinedAt: int, towns: int, footprint: num, lastOnline: { type: ['integer', 'null'] } }),
AllianceMemberList: obj({ serverTime: int, items: arr({ $ref: 'AllianceMember' }), next: { type: ['integer', 'null'] } }),
AllianceCreated: obj({ serverTime: int, allianceId: int, name: str, tag: str, sizeCap: int, role: str }),
AllianceInvite: obj({ id: int, operator: { $ref: 'OperatorBrief' }, invitedBy: { $ref: 'OperatorBrief' }, createdAt: int, expiresAt: int }),
AllianceInviteList: obj({ serverTime: int, items: arr({ $ref: 'AllianceInvite' }), next: { type: ['integer', 'null'] } }),
ReceivedInvite: obj({ id: int, operatorId: int, alliance: { $ref: 'AllianceBrief' }, invitedBy: { $ref: 'OperatorBrief' }, createdAt: int, expiresAt: int }),
ReceivedInviteList: obj({ serverTime: int, items: arr({ $ref: 'ReceivedInvite' }), next: { type: ['integer', 'null'] } }),
InviteResult: obj({ serverTime: int, inviteId: int, operatorId: int, expiresAt: int, changed: bool }),
Changed: obj({ serverTime: int, changed: bool }),
AllianceNote: obj({ id: int, authorId: int, text: str, createdAt: int, updatedAt: int }),
AllianceNoteResponse: obj({ serverTime: int, note: { $ref: 'AllianceNote' } }),
AllianceNoteList: obj({ serverTime: int, items: arr({ $ref: 'AllianceNote' }), next: { type: ['integer', 'null'] } }),
Relation: obj({ other: { type: 'object', additionalProperties: true }, state: str, since: int, pending: { type: ['object', 'null'], additionalProperties: true } }),
Proposal: obj({ id: int, other: { type: 'object', additionalProperties: true }, state: str, createdAt: int, expiresAt: int }),
Diplomacy: obj({ serverTime: int, allianceId: int, relations: arr({ $ref: 'Relation' }), proposalsIn: arr({ $ref: 'Proposal' }), proposalsOut: arr({ $ref: 'Proposal' }) }),
DiplomacyResult: obj({ serverTime: int, result: str, from: str, state: str }, ['serverTime', 'result', 'from', 'state']),
Message: obj({
id: int, kind: str, direction: str, thread: str, from: { $ref: 'OperatorBrief' }, to: { type: ['object', 'null'], additionalProperties: true },
alliance: { type: ['object', 'null'], additionalProperties: true }, text: str, createdAt: int, readAt: { type: ['integer', 'null'] },
}),
MessageList: obj({ serverTime: int, items: arr({ $ref: 'Message' }), next: { type: ['integer', 'null'] }, unread: int }, ['serverTime', 'items', 'next']),
MessageResponse: obj({ serverTime: int, message: { $ref: 'Message' } }),
MessageSent: obj({ serverTime: int, messageId: int, kind: str, recipients: int, createdAt: int }),
BlockList: obj({ serverTime: int, items: arr(obj({ operatorId: int, name: str, createdAt: int })), next: { type: ['integer', 'null'] } }),
RankOperator: obj({ rank: int, operatorId: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, allianceTag: { type: ['string', 'null'] }, towns: int, footprint: num }),
RankAlliance: obj({ rank: int, allianceId: int, name: str, tag: str, members: int, towns: int, footprint: num }),
RankBattle: obj({ rank: int, operatorId: int, name: str, allianceTag: { type: ['string', 'null'] }, attackPoints: num, defensePoints: num }),
RankOperators: obj({ serverTime: int, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankOperator' }), next: { type: ['integer', 'null'] } }),
RankAlliances: obj({ serverTime: int, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankAlliance' }), next: { type: ['integer', 'null'] } }),
RankBattles: obj({ serverTime: int, by: str, available: bool, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankBattle' }), next: { type: ['integer', 'null'] } }),
Ok: obj({ serverTime: int }),
};
require('./schemasMilitary')(schemas, { int, num, str, bool, obj, arr });
module.exports = { schemas, int, num, str, bool, obj, arr };

View file

@ -0,0 +1,42 @@
'use strict';
/* Response schemas of the military stage (merged into routes/schemas.js). Documentation only, like the others. */
module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj, arr }) {
const nint = { type: ['integer', 'null'] };
const free = { type: 'object', additionalProperties: true };
const Units = { type: 'object', additionalProperties: true, description: 'unit id -> count' };
const Cost = { $ref: 'Cost' };
Object.assign(schemas, {
Units,
TrainResult: obj({ serverTime: int, eventId: int, unit: str, count: int, building: str, startAt: int, dueAt: int, cost: Cost }),
ResearchResult: obj({ serverTime: int, eventId: int, unit: str, stat: str, toLevel: int, startedAt: int, dueAt: int, cost: Cost }),
MovementSent: obj({ serverTime: int, movementId: int, type: str, fromTownId: int, toTownId: nint, to: obj({ x: int, y: int }), units: Units, cargo: free, departAt: int, arriveAt: int, protectionEnded: bool }, ['serverTime', 'movementId', 'type', 'fromTownId', 'toTownId', 'departAt', 'arriveAt']),
RecallResult: obj({ serverTime: int, recalled: int, returnMovementId: int, arriveAt: int }),
WithdrawResult: obj({ serverTime: int, movementId: int, units: Units, arriveAt: int }),
MovementEnd: obj({ townId: nint, x: int, y: int, name: { type: ['string', 'null'] }, owner: { type: ['object', 'null'], additionalProperties: true } }, ['townId', 'x', 'y']),
Movement: obj({
id: int, type: str, status: str, ownerId: int, from: { $ref: 'MovementEnd' }, to: { $ref: 'MovementEnd' }, units: Units, cargo: free,
departAt: int, arriveAt: int, recallableUntil: nint, target: { type: ['string', 'null'] }, parentId: nint, incoming: bool,
}, ['id', 'type', 'status', 'from', 'to', 'departAt', 'arriveAt']),
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }),
Marked: obj({ serverTime: int, marked: int }),
ReportItem: obj({ id: int, type: str, createdAt: int, role: str, read: bool, summary: free }),
ReportList: obj({ serverTime: int, items: arr({ $ref: 'ReportItem' }), next: nint, unread: int }),
Report: obj({ id: int, type: str, createdAt: int, expiresAt: int, role: str, read: bool, summary: free, data: free }),
ReportResponse: obj({ serverTime: int, report: { $ref: 'Report' } }),
TileInfo: obj({
serverTime: int, x: int, y: int, type: str, bonus: { type: ['string', 'null'] },
distances: arr(obj({ townId: int, distance: num })), town: free, incumbent: free,
settle: obj({ possible: bool, code: { type: ['string', 'null'] }, footprint: num, footprintNeeded: num, maxDistance: int }),
}, ['serverTime', 'x', 'y', 'type', 'distances', 'settle']),
TownMilitary: obj({
units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free) }),
training: arr(obj({ id: int, unit: str, count: int, building: str, startAt: int, dueAt: int })),
trainable: arr(obj({ unit: str, building: str, role: str, cost: Cost, timeMs: int, missing: arr(free), locked: bool })),
research: obj({ levels: free, queue: { type: ['object', 'null'], additionalProperties: true }, speedBonus: num, maxLevel: int }),
transport: obj({ links: int, active: int, capacityPerLink: int }),
movements: obj({ outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }),
protectionUntil: int,
}),
});
if (schemas.Town && schemas.Town.properties) schemas.Town.properties.military = { $ref: 'TownMilitary' }; // optional: not in `required`
};

21
server/routes/units.js Normal file
View file

@ -0,0 +1,21 @@
'use strict';
/* Training queue and research of a POP (stage 3). */
const { reply } = require('../http');
const D = require('../../public/js/data.js');
function register(router, { commands }) {
const errs = ['unauthorized', 'not_found', 'validation_failed'];
router.post('/towns/:id/train', {
summary: 'Queue a batch of one unit type. Batches of the same training building run in order; units appear when the batch is done', tag: 'units',
body: { type: 'object', required: ['unit', 'count'], properties: { unit: { type: 'string', maxLength: 32, pattern: '^[a-z_]+$' }, count: { type: 'integer', minimum: 1, maximum: D.MILITARY.maxBatch } } },
response: { $ref: 'TrainResult' }, status: 201, errors: errs.concat(['unknown_unit', 'requirements_not_met', 'not_enough_resources', 'queue_full']),
}, ({ user, params, body }) => reply(201, commands.run('train', { userId: user.id, townId: params.id, unit: body.unit, count: body.count })));
router.post('/towns/:id/research', {
summary: 'Research +5% attack or defence for one unit type (one research at a time per POP, needs a Research lab)', tag: 'units',
body: { type: 'object', required: ['unit', 'stat'], properties: { unit: { type: 'string', maxLength: 32, pattern: '^[a-z_]+$' }, stat: { type: 'string', enum: ['attack', 'defence'] } } },
response: { $ref: 'ResearchResult' }, status: 201, errors: errs.concat(['unknown_unit', 'not_researchable', 'max_level', 'requirements_not_met', 'not_enough_resources', 'queue_full']),
}, ({ user, params, body }) => reply(201, commands.run('research', { userId: user.id, townId: params.id, unit: body.unit, stat: body.stat })));
}
module.exports = { register };

313
server/socialQueries.js Normal file
View file

@ -0,0 +1,313 @@
'use strict';
/*
* Read models for stage 5: alliances, diplomacy, messages, rankings. Like queries.js, every read first catches the
* event queue up to now and reads never write. List cursors: alliances/invites/notes by id ascending, messages newest
* first (cursor = the last id of the previous page, next page holds smaller ids), rankings by rank offset.
*/
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { GameError } = require('./errors');
const { loadWorld, hasTable } = require('./state');
const A = require('./alliances');
const { noteView } = require('./commands/allianceNote');
const S = D.SOCIAL;
const MAX_ID = Number.MAX_SAFE_INTEGER;
function createSocialQueries({ db, clock, scheduler }) {
const fresh = () => { scheduler.runDue(); return clock.now(); };
const opBrief = (id, name) => ({ operatorId: id, name });
// ---------------------------------------------------------------- footprint (rankings and alliance sums)
// operatorId -> { footprint, towns } for a whole world, from two queries (no per-town round trips).
function footprints(worldId, now) {
const world = loadWorld(db, worldId);
const towns = new Map();
for (const t of db.all('SELECT id, owner_id, footprint, res_at FROM towns WHERE world_id = ?', worldId)) {
towns.set(t.id, { owner: t.owner_id, town: { speed: world.speed, footprint: t.footprint, updatedAt: t.res_at, buildings: {} } });
}
for (const b of db.all('SELECT b.town_id AS tid, b.key AS key, b.level AS level FROM buildings b JOIN towns t ON t.id = b.town_id WHERE t.world_id = ?', worldId)) {
const e = towns.get(b.tid);
if (e) e.town.buildings[b.key] = { level: b.level };
}
const out = new Map();
for (const e of towns.values()) {
const cur = out.get(e.owner) || { footprint: 0, towns: 0 };
cur.footprint += R.footprintAt(e.town, now);
cur.towns += 1;
out.set(e.owner, cur);
}
return out;
}
// ---------------------------------------------------------------- alliances
function allianceInfo(a) {
const lead = db.get(`SELECT o.id AS id, o.name AS name FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE m.alliance_id = ? AND m.role = 'leader'`, a.id);
return {
id: a.id, worldId: a.world_id, name: a.name, tag: a.tag, sizeCap: A.effectiveCap(db, a), memberCount: A.memberCount(db, a.id),
leader: lead ? opBrief(lead.id, lead.name) : null, createdAt: a.created_at,
};
}
function permissionsOf(role) { return Object.keys(S.permissions).filter((k) => R.allianceCan(role, k)); }
// Caller's operator + membership in a world (default: their oldest operator).
function mine(userId, worldId) {
const now = fresh();
const op = A.operatorOf(db, userId, worldId);
const m = A.membership(db, op.id);
const a = m ? A.getAlliance(db, m.alliance_id) : null;
return {
serverTime: now, operatorId: op.id, worldId: op.world_id,
alliance: a ? allianceInfo(a) : null, role: m ? m.role : null, permissions: m ? permissionsOf(m.role) : [],
peeringLevel: A.peeringLevel(db, op.id),
};
}
function list(userId, { worldId, after, limit, q }) {
const now = fresh();
const op = A.operatorOf(db, userId, worldId);
limit = limit || 30;
const needle = q ? String(q).toLowerCase() : '';
const rows = db.all(`SELECT * FROM alliances WHERE world_id = ? AND id > ? AND (? = '' OR instr(lower(name), ?) > 0 OR instr(lower(tag), ?) > 0)
ORDER BY id LIMIT ?`, op.world_id, after || 0, needle, needle, needle, limit + 1);
const items = rows.slice(0, limit).map(allianceInfo);
return { serverTime: now, items, next: rows.length > limit ? items[items.length - 1].id : null };
}
function get(userId, id) {
const now = fresh();
const a = A.getAlliance(db, id);
const op = a && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, a.world_id);
if (!a || !op) throw new GameError('not_found', { what: 'alliance' });
const fp = footprints(a.world_id, now);
let footprint = 0;
for (const m of db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id)) footprint += (fp.get(m.operator_id) || { footprint: 0 }).footprint;
const mm = A.membership(db, op.id);
const info = allianceInfo(a);
info.footprint = Math.round(footprint * 100) / 100;
info.myRole = mm && mm.alliance_id === a.id ? mm.role : null;
info.relation = !mm ? null : mm.alliance_id === a.id ? 'same' : A.relationBetween(db, mm.alliance_id, a.id);
return { serverTime: now, alliance: info };
}
function memberOnly(userId, allianceId) {
const a = A.getAlliance(db, allianceId);
const op = a && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, a.world_id);
if (!a || !op) throw new GameError('not_found', { what: 'alliance' });
const m = A.membership(db, op.id);
if (!m || m.alliance_id !== a.id) throw new GameError('forbidden', { need: 'member' });
return { a, op, m };
}
// Member list with POP count, footprint and last online (newest token use of the user; tokens.last_used_at is
// refreshed at most once a minute by auth.authenticate). The list is bounded by the size cap, so it is not paginated.
function members(userId, allianceId) {
const now = fresh();
const { a } = memberOnly(userId, allianceId);
const fp = footprints(a.world_id, now);
const rows = db.all(`SELECT m.operator_id AS id, m.role AS role, m.joined_at AS joined, o.name AS name, o.as_number AS asn,
(SELECT MAX(t.last_used_at) FROM tokens t WHERE t.user_id = o.user_id) AS seen
FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE m.alliance_id = ?`, a.id);
const items = rows.map((r) => {
const f = fp.get(r.id) || { footprint: 0, towns: 0 };
return { operatorId: r.id, name: r.name, asNumber: r.asn, role: r.role, joinedAt: r.joined, towns: f.towns, footprint: Math.round(f.footprint * 100) / 100, lastOnline: r.seen };
}).sort((x, y) => R.roleRank(y.role) - R.roleRank(x.role) || x.name.localeCompare(y.name));
return { serverTime: now, items, next: null };
}
function invitesSent(userId, allianceId) {
const now = fresh();
const { a, m } = memberOnly(userId, allianceId);
if (!R.allianceCan(m.role, 'viewInvites')) throw new GameError('forbidden', { need: 'viewInvites', role: m.role });
const rows = db.all(`SELECT i.id, i.operator_id AS oid, i.created_at, i.expires_at, t.name AS tname, b.name AS bname, i.invited_by AS bid
FROM alliance_invites i JOIN operators t ON t.id = i.operator_id JOIN operators b ON b.id = i.invited_by
WHERE i.alliance_id = ? AND i.status = 'pending' AND i.expires_at > ? ORDER BY i.id`, a.id, now);
return { serverTime: now, items: rows.map((r) => ({ id: r.id, operator: opBrief(r.oid, r.tname), invitedBy: opBrief(r.bid, r.bname), createdAt: r.created_at, expiresAt: r.expires_at })), next: null };
}
function invitesReceived(userId) {
const now = fresh();
const rows = db.all(`SELECT i.id, i.alliance_id AS aid, i.created_at, i.expires_at, a.tag AS tag, a.name AS name, b.id AS bid, b.name AS bname, o.id AS oid
FROM alliance_invites i JOIN operators o ON o.id = i.operator_id JOIN alliances a ON a.id = i.alliance_id JOIN operators b ON b.id = i.invited_by
WHERE o.user_id = ? AND i.status = 'pending' AND i.expires_at > ? ORDER BY i.id`, userId, now);
return { serverTime: now, items: rows.map((r) => ({ id: r.id, operatorId: r.oid, alliance: { id: r.aid, tag: r.tag, name: r.name }, invitedBy: opBrief(r.bid, r.bname), createdAt: r.created_at, expiresAt: r.expires_at })), next: null };
}
function notes(userId, allianceId) {
const now = fresh();
const { a } = memberOnly(userId, allianceId);
const rows = db.all('SELECT * FROM alliance_notes WHERE alliance_id = ? ORDER BY id', a.id);
return { serverTime: now, items: rows.map(noteView), next: null };
}
function diplomacy(userId, allianceId) {
const now = fresh();
const { a } = memberOnly(userId, allianceId);
const brief = (id) => { const x = A.allianceBrief(db, id); return x || { id, tag: null, name: null }; };
const relations = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ? ORDER BY since, a_id', a.id, a.id).map((r) => {
const other = r.a_id === a.id ? r.b_id : r.a_id;
return {
other: brief(other), state: r.state, since: r.since,
pending: r.pending_to ? { to: r.pending_to, effectiveAt: r.pending_at, startedBy: r.pending_by, byUs: r.pending_by === a.id } : null,
};
});
const prop = (r, otherId) => ({ id: r.id, other: brief(otherId), state: r.state, createdAt: r.created_at, expiresAt: r.expires_at });
const incoming = db.all("SELECT * FROM alliance_proposals WHERE to_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id", a.id, now).map((r) => prop(r, r.from_id));
const outgoing = db.all("SELECT * FROM alliance_proposals WHERE from_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id", a.id, now).map((r) => prop(r, r.to_id));
return { serverTime: now, allianceId: a.id, relations, proposalsIn: incoming, proposalsOut: outgoing };
}
// ---------------------------------------------------------------- rankings
function rankingWorld(userId, worldId) {
const op = A.operatorOf(db, userId, worldId);
return op;
}
function page(rows, after, limit) {
const start = after || 0, n = limit || 50;
const slice = rows.slice(start, start + n).map((r, i) => Object.assign({ rank: start + i + 1 }, r));
return { items: slice, next: start + n < rows.length ? start + n : null };
}
function rankOperators(userId, { worldId, after, limit }) {
const now = fresh();
const me = rankingWorld(userId, worldId);
const fp = footprints(me.world_id, now);
const ops = db.all('SELECT o.id AS id, o.name AS name, o.as_number AS asn, a.id AS aid, a.tag AS tag FROM operators o LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?', me.world_id);
const rows = ops.map((o) => {
const f = fp.get(o.id) || { footprint: 0, towns: 0 };
return { operatorId: o.id, name: o.name, asNumber: o.asn, allianceId: o.aid, allianceTag: o.tag, towns: f.towns, footprint: Math.round(f.footprint * 100) / 100 };
}).sort((x, y) => y.footprint - x.footprint || x.operatorId - y.operatorId);
const you = rows.findIndex((r) => r.operatorId === me.id);
return Object.assign({ serverTime: now, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit));
}
function rankAlliances(userId, { worldId, after, limit }) {
const now = fresh();
const me = rankingWorld(userId, worldId);
const fp = footprints(me.world_id, now);
const byAlliance = new Map();
for (const o of db.all('SELECT o.id AS id, o.alliance_id AS aid FROM operators o WHERE o.world_id = ? AND o.alliance_id IS NOT NULL', me.world_id)) {
const cur = byAlliance.get(o.aid) || { footprint: 0, members: 0, towns: 0 };
const f = fp.get(o.id) || { footprint: 0, towns: 0 };
cur.footprint += f.footprint; cur.towns += f.towns; cur.members += 1;
byAlliance.set(o.aid, cur);
}
const rows = db.all('SELECT id, name, tag FROM alliances WHERE world_id = ?', me.world_id).map((a) => {
const s = byAlliance.get(a.id) || { footprint: 0, members: 0, towns: 0 };
return { allianceId: a.id, name: a.name, tag: a.tag, members: s.members, towns: s.towns, footprint: Math.round(s.footprint * 100) / 100 };
}).sort((x, y) => y.footprint - x.footprint || x.allianceId - y.allianceId);
const mm = A.membership(db, me.id);
const you = mm ? rows.findIndex((r) => r.allianceId === mm.alliance_id) : -1;
return Object.assign({ serverTime: now, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit));
}
// Battle points come from operator_stats, created by the military stage (migration 002). Without the table the
// list is simply empty (`available: false`).
function rankBattles(userId, { worldId, by, after, limit }) {
const now = fresh();
const me = rankingWorld(userId, worldId);
by = by || 'attack';
if (!hasTable(db, 'operator_stats')) return Object.assign({ serverTime: now, by, available: false, total: 0, you: null }, page([], after, limit));
const rows = db.all(`SELECT o.id AS id, o.name AS name, a.tag AS tag, s.attack_points AS att, s.defense_points AS def
FROM operator_stats s JOIN operators o ON o.id = s.operator_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?`, me.world_id)
.map((r) => ({ operatorId: r.id, name: r.name, allianceTag: r.tag, attackPoints: r.att || 0, defensePoints: r.def || 0 }))
.filter((r) => r.attackPoints > 0 || r.defensePoints > 0)
.sort((x, y) => {
const k = (r) => (by === 'defense' ? r.defensePoints : by === 'total' ? r.attackPoints + r.defensePoints : r.attackPoints);
return k(y) - k(x) || x.operatorId - y.operatorId;
});
const you = rows.findIndex((r) => r.operatorId === me.id);
return Object.assign({ serverTime: now, by, available: true, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit));
}
// ---------------------------------------------------------------- messages
const BASE = `SELECT m.*, s.name AS sname, t.name AS tname, r.operator_id AS rop, r.read_at AS rread
FROM messages m JOIN operators s ON s.id = m.sender_id LEFT JOIN operators t ON t.id = m.to_id
LEFT JOIN message_recipients r ON r.message_id = m.id AND r.operator_id = ?`;
const VISIBLE_IN = '(r.operator_id IS NOT NULL AND r.deleted_at IS NULL)';
const VISIBLE_OUT = '(m.sender_id = ? AND m.sender_deleted_at IS NULL)';
function msgView(row, meId) {
const out = row.sender_id === meId;
return {
id: row.id, kind: row.kind, direction: out ? 'out' : 'in', thread: row.thread,
from: opBrief(row.sender_id, row.sname), to: row.kind === 'dm' ? opBrief(row.to_id, row.tname) : null,
alliance: row.kind === 'alliance' ? { id: row.alliance_id, tag: row.alliance_tag } : null,
text: row.body, createdAt: row.created_at, readAt: out ? null : row.rread,
};
}
function messagePage(me, sql, params, limit) {
limit = limit || 30;
const rows = db.all(sql + ' ORDER BY m.id DESC LIMIT ?', me.id, ...params, limit + 1);
const items = rows.slice(0, limit).map((r) => msgView(r, me.id));
return { items, next: rows.length > limit ? items[items.length - 1].id : null };
}
const unreadCount = (opId) => db.get('SELECT COUNT(*) AS n FROM message_recipients WHERE operator_id = ? AND read_at IS NULL AND deleted_at IS NULL', opId).n;
function inbox(userId, { worldId, after, limit, unread }) {
const now = fresh();
const me = A.operatorOf(db, userId, worldId);
const sql = BASE + ' WHERE ' + VISIBLE_IN + (unread ? ' AND r.read_at IS NULL' : '') + ' AND m.id < ?';
return Object.assign({ serverTime: now, unread: unreadCount(me.id) }, messagePage(me, sql, [after || MAX_ID], limit));
}
function outbox(userId, { worldId, after, limit }) {
const now = fresh();
const me = A.operatorOf(db, userId, worldId);
return Object.assign({ serverTime: now }, messagePage(me, BASE + ' WHERE ' + VISIBLE_OUT + ' AND m.id < ?', [me.id, after || MAX_ID], limit));
}
// Conversation with one operator, both directions, newest first.
function thread(userId, otherId, { after, limit }) {
const now = fresh();
const other = db.get('SELECT id, world_id FROM operators WHERE id = ?', otherId);
const me = other && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, other.world_id);
if (!other || !me) throw new GameError('not_found', { what: 'operator' });
const key = 'dm:' + Math.min(me.id, other.id) + ':' + Math.max(me.id, other.id);
const sql = BASE + ' WHERE m.thread = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ') AND m.id < ?';
return Object.assign({ serverTime: now }, messagePage(me, sql, [key, me.id, after || MAX_ID], limit));
}
// Broadcasts of the caller's current alliance.
function allianceFeed(userId, { worldId, after, limit }) {
const now = fresh();
const me = A.operatorOf(db, userId, worldId);
const m = A.membership(db, me.id);
if (!m) throw new GameError('not_in_alliance');
const sql = BASE + ' WHERE m.thread = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ') AND m.id < ?';
return Object.assign({ serverTime: now }, messagePage(me, sql, ['alliance:' + m.alliance_id, me.id, after || MAX_ID], limit));
}
function message(userId, id) {
const now = fresh();
const m = db.get('SELECT world_id FROM messages WHERE id = ?', id);
const me = m && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, m.world_id);
if (!m || !me) throw new GameError('not_found', { what: 'message' });
const row = db.get(BASE + ' WHERE m.id = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ')', me.id, id, me.id);
if (!row) throw new GameError('not_found', { what: 'message' });
return { serverTime: now, message: msgView(row, me.id) };
}
function blocks(userId, { worldId }) {
const now = fresh();
const me = A.operatorOf(db, userId, worldId);
const rows = db.all('SELECT b.blocked_id AS id, o.name AS name, b.created_at AS at FROM message_blocks b JOIN operators o ON o.id = b.blocked_id WHERE b.operator_id = ? ORDER BY b.created_at, b.blocked_id', me.id);
return { serverTime: now, items: rows.map((r) => ({ operatorId: r.id, name: r.name, createdAt: r.at })), next: null };
}
return {
mine, list, get, members, invitesSent, invitesReceived, notes, diplomacy,
rankOperators, rankAlliances, rankBattles,
inbox, outbox, thread, allianceFeed, message, blocks, footprints,
};
}
module.exports = { createSocialQueries };

View file

@ -35,6 +35,10 @@ function unitDraw(db, townId) {
const rows = db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId);
let draw = 0;
for (const r of rows) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
// Reinforcements draw from the host, not from their owner.
if (hasTable(db, 'stationed')) {
for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ?', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
}
return draw;
}

26
server/text.js Normal file
View file

@ -0,0 +1,26 @@
'use strict';
/*
* Plain-text hygiene for everything players type that other players read (messages, notes, alliance names).
* Strips control characters and the invisible/bidirectional formatting characters that can be used to spoof text
* ("Trojan Source" style reordering, zero-width padding to hide content), normalises to NFC and fixes lone surrogates.
* Newlines and tabs survive only in multiline text.
*/
// C0 (except \t \n, CR is normalised first), DEL + C1, ALM, zero-width space, LRM/RLM, bidi embeddings/overrides
// (202A-202E), word joiner and invisible operators (2060-2064), bidi isolates and deprecated formatting (2066-206F),
// BOM, interlinear annotation, and the invisible Unicode tag block. ZWJ/ZWNJ (200C/200D) stay: emoji and some scripts need them.
const STRIP = new RegExp('[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200B\\u200E\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u206F\\uFEFF\\uFFF9-\\uFFFB\\u{E0000}-\\u{E007F}]', 'gu');
function cleanText(input, opts) {
const multiline = !!(opts && opts.multiline);
let s = String(input === undefined || input === null ? '' : input);
if (s.toWellFormed) s = s.toWellFormed();
s = s.normalize('NFC').replace(/\r\n?/g, '\n').replace(/[\u2028\u2029\u0085]/g, '\n').replace(STRIP, '');
if (multiline) s = s.replace(/[ \t]+\n/g, '\n').replace(/\n{4,}/g, '\n\n\n');
else s = s.replace(/[\n\t]+/g, ' ').replace(/ {2,}/g, ' ');
return s.trim();
}
// Length in code points (what a player counts), not UTF-16 units.
const textLength = (s) => { let n = 0; for (const _ of s) n++; return n; }; // eslint-disable-line no-unused-vars
module.exports = { cleanText, textLength };