'use strict'; const { GameError } = require('../errors'); const { reply } = require('../http'); const crypto = require('crypto'); const { sha256, newToken, hashPassword: hashRaw, verifyPassword: verifyRaw } = require('../auth'); const { Limiter } = require('../http'); // scrypt is CPU heavy: only a few run at once, the rest are told to back off instead of queueing up. let busy = 0; const MAX_SCRYPT = 4; async function limited(fn) { if (busy >= MAX_SCRYPT) throw new GameError('rate_limited', { retryAfter: 2 }); busy++; try { return await fn(); } finally { busy--; } } const hashPassword = (p) => limited(() => hashRaw(p)); const verifyPassword = (p, h) => limited(() => verifyRaw(p, h)); const safeEq = (a, b) => { const x = Buffer.from(String(a)), y = Buffer.from(String(b)); return x.length === y.length && crypto.timingSafeEqual(x, y); }; function register(router, { db, clock, commands, queries, auth, opts }) { const userLimit = new Limiter(0.02, 6, 5000); // per username: ~6 tries, then one per 50 s, whoever the IP is 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 && !safeEq(body.invite || '', opts.signupCode)) throw new GameError('signup_closed'); if (db.get('SELECT 1 AS x FROM users WHERE username = ?', body.username)) throw new GameError('username_taken'); 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 }) => { if (!userLimit.take(body.username.toLowerCase())) throw new GameError('rate_limited', { retryAfter: 30 }); 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 };