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
61 lines
3.7 KiB
JavaScript
61 lines
3.7 KiB
JavaScript
'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 };
|