Upstream/server/commands/messageSend.js
jvanvik 249818a7aa 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
2026-10-11 18:32:36 +02:00

72 lines
4.7 KiB
JavaScript

'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 };
};