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

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