Stage 0-2 server spine: db, scheduler, REST, auth, economy, map
Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map + spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused. Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet. NOT done: military, expansion, social, client, push, deploy docs, bots/admin. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
9fa76d53a8
commit
b56b13880e
39 changed files with 4450 additions and 0 deletions
61
server/routes/auth.js
Normal file
61
server/routes/auth.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
'use strict';
|
||||
const { GameError } = require('../errors');
|
||||
const { reply } = require('../http');
|
||||
const { sha256, newToken, hashPassword, verifyPassword } = require('../auth');
|
||||
|
||||
function register(router, { db, clock, commands, queries, auth, opts }) {
|
||||
const creds = {
|
||||
username: { type: 'string', minLength: 3, maxLength: 20, pattern: '^[A-Za-z0-9_-]+$' },
|
||||
password: { type: 'string', minLength: 8, maxLength: 128 },
|
||||
device: { type: 'string', maxLength: 40 },
|
||||
};
|
||||
|
||||
router.post('/auth/signup', {
|
||||
summary: 'Create an account, join the world and get a bearer token', tag: 'auth', auth: false, limit: 'auth',
|
||||
body: { type: 'object', required: ['username', 'password'], properties: Object.assign({ invite: { type: 'string', maxLength: 64 }, worldId: { type: 'integer', minimum: 1 } }, creds) },
|
||||
response: { $ref: 'AuthResult' }, status: 201, errors: ['validation_failed', 'username_taken', 'signup_closed', 'world_full', 'rate_limited'],
|
||||
}, async ({ body }) => {
|
||||
if (opts.signupCode && body.invite !== opts.signupCode) throw new GameError('signup_closed');
|
||||
const passHash = await hashPassword(body.password);
|
||||
const token = newToken();
|
||||
const r = commands.run('signup', { username: body.username, passHash, tokenHash: sha256(token), device: body.device, worldId: body.worldId });
|
||||
const me = queries.me(r.userId);
|
||||
return reply(201, { token, tokenId: r.tokenId, user: { id: r.userId, username: body.username }, operators: me.operators });
|
||||
});
|
||||
|
||||
router.post('/auth/login', {
|
||||
summary: 'Log in on a device and get a bearer token', tag: 'auth', auth: false, limit: 'auth',
|
||||
body: { type: 'object', required: ['username', 'password'], properties: creds },
|
||||
response: { $ref: 'AuthResult' }, errors: ['validation_failed', 'invalid_credentials', 'forbidden', 'rate_limited'],
|
||||
}, async ({ body }) => {
|
||||
const u = db.get('SELECT id, username, pass_hash, banned FROM users WHERE username = ?', body.username);
|
||||
const ok = await verifyPassword(body.password, u && u.pass_hash);
|
||||
if (!u || !ok) throw new GameError('invalid_credentials');
|
||||
if (u.banned) throw new GameError('forbidden');
|
||||
const { token, tokenId } = auth.issueToken(u.id, body.device, clock.now());
|
||||
return { token, tokenId, user: { id: u.id, username: u.username }, operators: queries.me(u.id).operators };
|
||||
});
|
||||
|
||||
router.post('/auth/logout', { summary: 'Revoke the token used for this request', tag: 'auth', response: { $ref: 'Ok' }, errors: ['unauthorized'] },
|
||||
({ user, tokenId }) => {
|
||||
db.run('UPDATE tokens SET revoked_at = ? WHERE id = ? AND user_id = ?', clock.now(), tokenId, user.id);
|
||||
return {};
|
||||
});
|
||||
|
||||
router.get('/auth/tokens', {
|
||||
summary: 'List this account\'s active device tokens', tag: 'auth',
|
||||
response: { type: 'object', required: ['serverTime', 'tokens'], properties: { serverTime: { type: 'integer' }, tokens: { type: 'array', items: { $ref: 'Token' } } } }, errors: ['unauthorized'],
|
||||
}, ({ user, tokenId }) => ({
|
||||
tokens: db.all('SELECT id, device, created_at, last_used_at FROM tokens WHERE user_id = ? AND revoked_at IS NULL ORDER BY id', user.id)
|
||||
.map((t) => ({ id: t.id, device: t.device, createdAt: t.created_at, lastUsedAt: t.last_used_at, current: t.id === tokenId })),
|
||||
}));
|
||||
|
||||
router.del('/auth/tokens/:tokenId', { summary: 'Revoke one of this account\'s tokens', tag: 'auth', response: { $ref: 'Ok' }, errors: ['unauthorized', 'not_found'] },
|
||||
({ user, params }) => {
|
||||
const r = db.run('UPDATE tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL', clock.now(), params.tokenId, user.id);
|
||||
if (!r.changes) throw new GameError('not_found', { what: 'token' });
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { register };
|
||||
9
server/routes/index.js
Normal file
9
server/routes/index.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
'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')];
|
||||
|
||||
function register(router, services) {
|
||||
for (const f of files) f.register(router, services);
|
||||
}
|
||||
|
||||
module.exports = { register };
|
||||
9
server/routes/map.js
Normal file
9
server/routes/map.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
'use strict';
|
||||
function register(router, { queries }) {
|
||||
router.get('/map', {
|
||||
summary: 'Map viewport: rural areas, incumbent sites and POPs within (x±r, y±r); land tiles are implied', tag: 'map',
|
||||
query: { type: 'object', required: ['x', 'y', 'r'], properties: { x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, r: { type: 'integer', minimum: 1, maximum: 40 }, worldId: { type: 'integer', minimum: 1 } } },
|
||||
response: { $ref: 'MapResponse' }, errors: ['unauthorized', 'validation_failed', 'not_found'],
|
||||
}, ({ user, query }) => queries.map(user.id, { worldId: query.worldId, x: query.x, y: query.y, r: query.r }));
|
||||
}
|
||||
module.exports = { register };
|
||||
12
server/routes/me.js
Normal file
12
server/routes/me.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
'use strict';
|
||||
function register(router, { queries }) {
|
||||
router.get('/me', { summary: 'The current user, their operators and POPs', tag: 'me', response: { $ref: 'Me' }, errors: ['unauthorized'] },
|
||||
({ user }) => queries.me(user.id));
|
||||
|
||||
router.get('/notifications', {
|
||||
summary: 'Notifications for this user (cursor: after = last seen id)', tag: 'me',
|
||||
query: { type: 'object', properties: { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } } },
|
||||
response: { $ref: 'NotificationList' }, errors: ['unauthorized', 'validation_failed'],
|
||||
}, ({ user, query }) => queries.notifications(user.id, query));
|
||||
}
|
||||
module.exports = { register };
|
||||
43
server/routes/schemas.js
Normal file
43
server/routes/schemas.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
'use strict';
|
||||
/* Shared response schemas (JSON-schema subset), referenced from route meta as { $ref: 'Name' } and emitted into
|
||||
* openapi.json components. Responses are documentation (and checked by test/api-contract.test.js), not enforced at runtime. */
|
||||
const int = { type: 'integer' };
|
||||
const num = { type: 'number' };
|
||||
const str = { type: 'string' };
|
||||
const bool = { type: 'boolean' };
|
||||
const obj = (properties, required) => ({ type: 'object', properties, required: required || Object.keys(properties), additionalProperties: true });
|
||||
const arr = (items) => ({ type: 'array', items });
|
||||
|
||||
const Cost = obj({ fiber: int, hardware: int, capital: int });
|
||||
|
||||
const schemas = {
|
||||
Cost,
|
||||
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' }) }),
|
||||
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 }),
|
||||
BuildPlan: obj({ ok: bool, code: { type: ['string', 'null'] }, toLevel: int, cost: { $ref: 'Cost' }, durationMs: int, missing: arr(obj({ type: str, level: int, have: int })) }, ['ok', 'code', 'toLevel']),
|
||||
BuildingView: obj({ key: str, type: str, kind: str, level: int, maxLevel: int, next: { $ref: 'BuildPlan' } }),
|
||||
QueueEntry: obj({ id: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int }),
|
||||
ResourceView: obj({ amount: num, rate: num, cap: num }),
|
||||
Town: obj({
|
||||
id: int, name: str, x: int, y: int, isCapital: bool, ownerId: int, worldId: int, loyalty: num, footprint: num, footprintPerDay: num,
|
||||
resources: obj({ fiber: { $ref: 'ResourceView' }, hardware: { $ref: 'ResourceView' }, capital: { $ref: 'ResourceView' } }),
|
||||
power: obj({ out: num, draw: num, net: num, buffer: num, bufferCap: num, bufferRate: num, online: bool }),
|
||||
buildings: arr({ $ref: 'BuildingView' }), queue: arr({ $ref: 'QueueEntry' }), queueSlots: int,
|
||||
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 }) }),
|
||||
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'] } }),
|
||||
Ok: obj({ serverTime: int }),
|
||||
};
|
||||
|
||||
module.exports = { schemas, int, num, str, bool, obj, arr };
|
||||
27
server/routes/towns.js
Normal file
27
server/routes/towns.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
'use strict';
|
||||
const { reply } = require('../http');
|
||||
|
||||
function register(router, { queries, commands }) {
|
||||
const errs = ['unauthorized', 'not_found'];
|
||||
|
||||
router.get('/towns/:id', { summary: 'Full state of one of your POPs: resources, power, buildings, build queue', tag: 'towns', response: { $ref: 'TownResponse' }, errors: errs },
|
||||
({ user, params }) => queries.town(user.id, params.id));
|
||||
|
||||
router.post('/towns/:id/build', {
|
||||
summary: 'Build or upgrade a building (fields f1..f18 or an infrastructure building type) by one level', tag: 'towns',
|
||||
body: { type: 'object', required: ['key'], properties: { key: { type: 'string', maxLength: 32, pattern: '^[a-z0-9_]+$' } } },
|
||||
response: { $ref: 'BuildResult' }, status: 201,
|
||||
errors: errs.concat(['validation_failed', 'unknown_building', 'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources']),
|
||||
}, ({ user, params, body }) => {
|
||||
return reply(201, commands.run('build', { userId: user.id, townId: params.id, key: body.key }));
|
||||
});
|
||||
|
||||
router.del('/towns/:id/queue/:eventId', { summary: 'Cancel a running build and get 80% of its cost back', tag: 'towns', response: { $ref: 'Ok' }, errors: errs },
|
||||
({ user, params }) => { commands.run('cancelBuild', { userId: user.id, townId: params.id, eventId: params.eventId }); return {}; });
|
||||
|
||||
router.post('/towns/:id/rename', {
|
||||
summary: 'Rename a POP', tag: 'towns', body: { type: 'object', required: ['name'], properties: { name: { type: 'string', minLength: 2, maxLength: 40 } } },
|
||||
response: { type: 'object', required: ['serverTime', 'name'], properties: { serverTime: { type: 'integer' }, name: { type: 'string' } } }, errors: errs.concat(['validation_failed']),
|
||||
}, ({ user, params, body }) => commands.run('renameTown', { userId: user.id, townId: params.id, name: body.name }));
|
||||
}
|
||||
module.exports = { register };
|
||||
Loading…
Add table
Add a link
Reference in a new issue