Upstream/server/socialQueries.js
jvanvik b18645dca1 Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push
(docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels.
Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js,
rankings DoS, static headers, ...): fixes follow in the next commit.
NOT done: bots/balance, e2e suite, real-device checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 19:05:03 +02:00

313 lines
18 KiB
JavaScript

'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, footprints,
inbox, outbox, thread, allianceFeed, message, blocks, footprints,
};
}
module.exports = { createSocialQueries };