ChessUp/src/server/httpApi.ts

612 lines
22 KiB
TypeScript

import fs from 'node:fs';
import type http from 'node:http';
import path from 'node:path';
import { RATED_CATEGORIES } from '../shared/timeControl';
import type { ColorPreference, RatedCategory, TimeCategory, UserProfile, UserSummary } from '../shared/types';
import {
SESSION_COOKIE_NAME,
SlidingRateLimiter,
buildClearSessionCookie,
buildSessionCookie,
createSessionToken,
hashPassword,
hashSessionToken,
isSameOriginAllowed,
parseCookies,
validatePassword,
validateUsername,
verifyPassword
} from './auth';
import type { AppConfig } from './config';
import type { ChessDatabase } from './db';
import type { GameManager } from './gameManager';
import type { LobbyManager } from './lobbyManager';
import type { WsHub } from './wsServer';
const MIME_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon'
};
const MAX_BODY_BYTES = 1_048_576;
function sendJson(res: http.ServerResponse, status: number, body: unknown, extraHeaders?: Record<string, string>): void {
const payload = JSON.stringify(body);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
...(extraHeaders || {})
});
res.end(payload);
}
function readJsonBody(req: http.IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > MAX_BODY_BYTES) {
reject(Object.assign(new Error('Request body too large'), { statusCode: 413 }));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => {
if (chunks.length === 0) {
resolve({});
return;
}
try {
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
resolve(parsed as Record<string, unknown>);
} else {
reject(Object.assign(new Error('Expected JSON object'), { statusCode: 400 }));
}
} catch {
reject(Object.assign(new Error('Invalid JSON payload'), { statusCode: 400 }));
}
});
req.on('error', (err) => reject(err));
});
}
function getClientIp(req: http.IncomingMessage): string {
const cfIp = req.headers['cf-connecting-ip'];
if (typeof cfIp === 'string' && cfIp.trim()) {
return cfIp.trim();
}
const fwd = req.headers['x-forwarded-for'];
if (typeof fwd === 'string' && fwd.trim()) {
return fwd.split(',')[0]!.trim();
}
return req.socket.remoteAddress || 'unknown';
}
export function createHttpHandler(deps: {
config: AppConfig;
db: ChessDatabase;
lobbyManager: LobbyManager;
gameManager: GameManager;
wsHub: WsHub;
}): http.RequestListener {
const { config, db, lobbyManager, gameManager, wsHub } = deps;
const authRateLimiter = new SlidingRateLimiter(40, 5 * 60 * 1000, config.disableRateLimit);
const analysisRateLimiter = new SlidingRateLimiter(20, 10 * 60 * 1000, config.disableRateLimit);
const publicDirResolved = path.resolve(config.publicDir);
function getSessionContext(req: http.IncomingMessage): { user: UserSummary | null; tokenHash: string | null } {
const cookies = parseCookies(req.headers.cookie);
const sid = cookies[SESSION_COOKIE_NAME];
if (!sid) return { user: null, tokenHash: null };
const tokenHash = hashSessionToken(sid);
const user = db.findUserBySessionTokenHash(tokenHash);
if (!user) return { user: null, tokenHash: null };
return { user, tokenHash };
}
function serveStatic(res: http.ServerResponse, urlPath: string, method: string): void {
let relPath = urlPath;
if (relPath === '/' || !path.extname(relPath)) {
relPath = '/index.html';
}
const safeRel = relPath.replace(/^\/+/, '');
const resolved = path.resolve(publicDirResolved, safeRel);
if (resolved !== publicDirResolved && !resolved.startsWith(publicDirResolved + path.sep)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
let targetFile = resolved;
if (!fs.existsSync(targetFile) || fs.statSync(targetFile).isDirectory()) {
targetFile = path.join(publicDirResolved, 'index.html');
}
if (!fs.existsSync(targetFile)) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(method === 'HEAD' ? undefined : 'Not built yet. Run npm run build.');
return;
}
const ext = path.extname(targetFile);
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
const isHtml = ext === '.html';
const cacheControl = isHtml ? 'no-cache' : 'public, max-age=300';
const content = fs.readFileSync(targetFile);
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': cacheControl,
'Content-Length': content.length
});
res.end(method === 'HEAD' ? undefined : content);
}
return async (req, res) => {
try {
const method = (req.method || 'GET').toUpperCase();
const parsedUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
let pathname: string;
try {
pathname = decodeURIComponent(parsedUrl.pathname);
} catch {
sendJson(res, 400, { error: 'Malformed URL path.' });
return;
}
if (!pathname.startsWith('/api/')) {
if (method !== 'GET' && method !== 'HEAD') {
sendJson(res, 405, { error: 'Method not allowed' });
return;
}
serveStatic(res, pathname, method);
return;
}
// CSRF protection on mutating API calls
if (method !== 'GET' && method !== 'HEAD' && !isSameOriginAllowed(req)) {
sendJson(res, 403, { error: 'Origin mismatch' });
return;
}
const { user, tokenHash } = getSessionContext(req);
const segments = pathname.slice(5).split('/').filter(Boolean); // after /api/
if (segments[0] === 'health' && !segments[1] && method === 'GET') {
sendJson(res, 200, { ok: true });
return;
}
// ---- AUTH ----
if (segments[0] === 'auth') {
if (segments[1] === 'register' && method === 'POST') {
if (!authRateLimiter.allow(getClientIp(req))) {
sendJson(res, 429, { error: 'Too many authentication attempts. Try again shortly.' });
return;
}
const body = await readJsonBody(req);
const uCheck = validateUsername(String(body['username'] || ''));
if (!uCheck.ok) {
sendJson(res, 400, { error: uCheck.error });
return;
}
const pCheck = validatePassword(String(body['password'] || ''));
if (!pCheck.ok) {
sendJson(res, 400, { error: pCheck.error });
return;
}
if (db.findUserRowByUsername(uCheck.username)) {
sendJson(res, 409, { error: 'Username is already taken.' });
return;
}
const { hashHex, saltHex } = hashPassword(String(body['password']));
const created = db.createUser(uCheck.username, hashHex, saltHex);
const { token, tokenHash: newHash } = createSessionToken();
db.createSession(newHash, created.id, Date.now() + config.sessionTtlMs);
sendJson(
res,
201,
{ user: created },
{ 'Set-Cookie': buildSessionCookie(token, config.sessionTtlMs / 1000, config.cookieSecure) }
);
return;
}
if (segments[1] === 'login' && method === 'POST') {
if (!authRateLimiter.allow(getClientIp(req))) {
sendJson(res, 429, { error: 'Too many login attempts. Try again shortly.' });
return;
}
const body = await readJsonBody(req);
const username = String(body['username'] || '').trim();
const password = String(body['password'] || '');
const row = db.findUserRowByUsername(username);
if (!row || !verifyPassword(password, row.password_hash, row.password_salt)) {
sendJson(res, 401, { error: 'Invalid username or password.' });
return;
}
db.updateLastSeen(row.id);
const { token, tokenHash: newHash } = createSessionToken();
db.createSession(newHash, row.id, Date.now() + config.sessionTtlMs);
const summary = db.getUserSummaryById(row.id)!;
sendJson(
res,
200,
{ user: summary },
{ 'Set-Cookie': buildSessionCookie(token, config.sessionTtlMs / 1000, config.cookieSecure) }
);
return;
}
if (segments[1] === 'logout' && method === 'POST') {
if (tokenHash) {
db.deleteSession(tokenHash);
}
sendJson(
res,
200,
{ ok: true },
{ 'Set-Cookie': buildClearSessionCookie(config.cookieSecure) }
);
return;
}
if (segments[1] === 'me' && method === 'GET') {
const activeGameId = user ? gameManager.getUserActiveGameId(user.id) : null;
sendJson(res, 200, { user, activeGameId });
return;
}
if (segments[1] === 'password' && method === 'POST') {
if (!user) {
sendJson(res, 401, { error: 'Authentication required.' });
return;
}
const body = await readJsonBody(req);
const currentPw = String(body['currentPassword'] || '');
const newPw = String(body['newPassword'] || '');
const row = db.findUserRowById(user.id);
if (!row || !verifyPassword(currentPw, row.password_hash, row.password_salt)) {
sendJson(res, 400, { error: 'Current password is incorrect.' });
return;
}
const pCheck = validatePassword(newPw);
if (!pCheck.ok) {
sendJson(res, 400, { error: pCheck.error });
return;
}
const { hashHex, saltHex } = hashPassword(newPw);
db.updatePassword(user.id, hashHex, saltHex);
sendJson(res, 200, { ok: true });
return;
}
}
// ---- USERS ----
if (segments[0] === 'users') {
if (segments[1] === 'search' && method === 'GET') {
const q = parsedUrl.searchParams.get('q') || '';
const users = db.searchUsers(q, user?.id, 20);
sendJson(res, 200, { users });
return;
}
if (segments[1] && segments[2] === 'games' && method === 'GET') {
const target = db.getUserSummaryByUsername(segments[1]);
if (!target) {
sendJson(res, 404, { error: 'User not found.' });
return;
}
const catParam = parsedUrl.searchParams.get('category') || '';
const resParam = parsedUrl.searchParams.get('result') || '';
const oppParam = parsedUrl.searchParams.get('opponent') || '';
const vsBotParam = parsedUrl.searchParams.get('vsBot') || '';
const page = Number(parsedUrl.searchParams.get('page')) || 1;
const limit = Number(parsedUrl.searchParams.get('limit')) || 20;
const validCat: TimeCategory | undefined =
catParam === 'bullet' ||
catParam === 'blitz' ||
catParam === 'rapid' ||
catParam === 'classical' ||
catParam === 'unlimited'
? catParam
: undefined;
const validRes = resParam === 'win' || resParam === 'loss' || resParam === 'draw' ? resParam : undefined;
const validVsBot = vsBotParam === 'only' || vsBotParam === 'exclude' ? vsBotParam : undefined;
const history = db.listUserGames(target.id, {
category: validCat,
result: validRes,
opponent: oppParam || undefined,
vsBot: validVsBot,
page,
limit
});
sendJson(res, 200, history);
return;
}
if (segments[1] && !segments[2] && method === 'GET') {
const target = db.getUserSummaryByUsername(segments[1]);
if (!target) {
sendJson(res, 404, { error: 'User not found.' });
return;
}
const presence = lobbyManager.getPresence(target.id);
const profile: UserProfile = {
user: target,
onlineStatus: presence.onlineStatus,
activeGameId: presence.activeGameId,
wdl: db.getUserWdl(target.id),
ratingHistory: db.getRatingHistory(target.id, 100)
};
if (user && user.id !== target.id) {
profile.friendship = db.getFriendship(user.id, target.id);
profile.headToHead = db.getHeadToHead(user.id, target.id);
}
sendJson(res, 200, { profile });
return;
}
}
// ---- LEADERBOARD ----
if (segments[0] === 'leaderboard' && method === 'GET') {
const catParam = parsedUrl.searchParams.get('category') || 'blitz';
const cat: RatedCategory = (RATED_CATEGORIES as ReadonlyArray<string>).includes(catParam)
? (catParam as RatedCategory)
: 'blitz';
const limit = Math.min(100, Math.max(1, Number(parsedUrl.searchParams.get('limit')) || 50));
sendJson(res, 200, { category: cat, entries: db.getLeaderboard(cat, limit) });
return;
}
// ---- FRIENDS ----
if (segments[0] === 'friends') {
if (!user) {
sendJson(res, 401, { error: 'Authentication required.' });
return;
}
if (!segments[1] && method === 'GET') {
const list = db.listFriendsAndRequests(user.id, (uid) => lobbyManager.getPresence(uid));
const challenges = lobbyManager.getUserChallenges(user.id);
sendJson(res, 200, { ...list, challenges });
return;
}
if (segments[1] === 'request' && method === 'POST') {
const body = await readJsonBody(req);
let targetUser: UserSummary | null = null;
if (typeof body['userId'] === 'number') {
targetUser = db.getUserSummaryById(body['userId']);
} else if (typeof body['username'] === 'string') {
targetUser = db.getUserSummaryByUsername(body['username']);
}
if (!targetUser) {
sendJson(res, 404, { error: 'Player not found.' });
return;
}
if (targetUser.id === user.id) {
sendJson(res, 400, { error: 'You cannot add yourself as a friend.' });
return;
}
const outcome = db.sendFriendRequest(user.id, targetUser.id);
wsHub.sendToUser(targetUser.id, { type: 'friend:update' });
wsHub.sendToUser(user.id, { type: 'friend:update' });
sendJson(res, 200, { outcome });
return;
}
if (segments[1] === 'respond' && method === 'POST') {
const body = await readJsonBody(req);
const otherId = Number(body['userId']);
const accept = Boolean(body['accept']);
if (!Number.isInteger(otherId)) {
sendJson(res, 400, { error: 'Invalid userId.' });
return;
}
const ok = db.respondFriendRequest(user.id, otherId, accept);
if (!ok) {
sendJson(res, 404, { error: 'Pending friend request not found.' });
return;
}
wsHub.sendToUser(otherId, { type: 'friend:update' });
wsHub.sendToUser(user.id, { type: 'friend:update' });
sendJson(res, 200, { ok: true });
return;
}
if (segments[1] && method === 'DELETE') {
const otherId = Number(segments[1]);
if (!Number.isInteger(otherId)) {
sendJson(res, 400, { error: 'Invalid userId.' });
return;
}
db.removeFriendOrRequest(user.id, otherId);
wsHub.sendToUser(otherId, { type: 'friend:update' });
wsHub.sendToUser(user.id, { type: 'friend:update' });
sendJson(res, 200, { ok: true });
return;
}
}
// ---- LOBBY & INVITES ----
if (segments[0] === 'lobby' && !segments[1] && method === 'GET') {
sendJson(res, 200, { seeks: lobbyManager.listSeeks() });
return;
}
if (segments[0] === 'invites') {
if (!segments[1] && method === 'POST') {
if (!user) {
sendJson(res, 401, { error: 'Sign in to create an invite link.' });
return;
}
const body = await readJsonBody(req);
const resInvite = lobbyManager.createInvite(user.id, {
initialMs: Number(body['initialMs']) || 0,
incrementMs: Number(body['incrementMs']) || 0,
rated: Boolean(body['rated']),
colorPref: (body['colorPref'] as ColorPreference) || 'random'
});
if (!resInvite.ok) {
sendJson(res, 400, { error: resInvite.error });
return;
}
sendJson(res, 201, { invite: resInvite.invite });
return;
}
if (segments[1] && !segments[2] && method === 'GET') {
const invite = lobbyManager.getInvite(segments[1]);
if (!invite) {
sendJson(res, 404, { error: 'Invite link is invalid or expired.' });
return;
}
sendJson(res, 200, { invite });
return;
}
if (segments[1] && segments[2] === 'accept' && method === 'POST') {
if (!user) {
sendJson(res, 401, { error: 'Sign in to accept this challenge.' });
return;
}
const resAccept = lobbyManager.acceptInvite(user.id, segments[1]);
if (!resAccept.ok) {
sendJson(res, 400, { error: resAccept.error });
return;
}
sendJson(res, 200, { gameId: resAccept.gameId });
return;
}
}
// ---- GAMES & BOT GAMES & ANALYTICS ----
if (segments[0] === 'games') {
if (segments[1] === 'bot' && method === 'POST') {
if (!user) {
sendJson(res, 401, { error: 'Sign in to play against Stockfish.' });
return;
}
const body = await readJsonBody(req);
const created = gameManager.createBotGame(user.id, {
level: Number(body['level']) || 1,
colorPref: (body['colorPref'] as ColorPreference) || 'random',
initialMs: Number(body['initialMs']) || 0,
incrementMs: Number(body['incrementMs']) || 0
});
if (!created.ok) {
sendJson(res, 400, { error: created.error });
return;
}
sendJson(res, 201, { gameId: created.gameId });
return;
}
const gameId = segments[1];
if (gameId && segments[2] === 'pgn' && method === 'GET') {
const active = gameManager.getGameState(gameId);
let pgn: string | null = active?.pgn ?? null;
if (!pgn) {
pgn = db.getGameById(gameId)?.pgn ?? null;
}
if (!pgn) {
sendJson(res, 404, { error: 'PGN not found for this game.' });
return;
}
const safeId = gameId.replace(/[^A-Za-z0-9_-]/g, '');
res.writeHead(200, {
'Content-Type': 'application/x-chess-pgn; charset=utf-8',
'Content-Disposition': `attachment; filename="chessup-${safeId || 'game'}.pgn"`
});
res.end(pgn);
return;
}
if (gameId && segments[2] === 'analysis') {
if (method === 'GET') {
const report = db.getAnalysis(gameId);
if (!report) {
const stored = db.getGameById(gameId);
if (!stored) {
sendJson(res, 404, { error: 'Saved game not found.' });
return;
}
sendJson(res, 200, { report: null });
return;
}
sendJson(res, 200, { report });
return;
}
if (method === 'POST') {
if (!analysisRateLimiter.allow(getClientIp(req))) {
sendJson(res, 429, { error: 'Too many analysis requests. Try again shortly.' });
return;
}
const body = await readJsonBody(req);
const depthOpt = typeof body['depth'] === 'number' ? body['depth'] : undefined;
const triggered = gameManager.requestGameAnalysis(gameId, depthOpt, (msg) => {
wsHub.broadcastToAnalysis(gameId, msg);
});
if (!triggered.ok) {
sendJson(res, triggered.status, { error: triggered.error });
return;
}
const code = triggered.report.status === 'done' ? 200 : 202;
sendJson(res, code, { report: triggered.report });
return;
}
}
if (gameId && !segments[2] && method === 'GET') {
const active = gameManager.getGameState(gameId);
if (active && !active.finished) {
sendJson(res, 200, { kind: 'active', game: active });
return;
}
const stored = db.getGameById(gameId);
if (stored) {
const analysis = db.getAnalysis(gameId);
sendJson(res, 200, { kind: 'stored', game: stored, analysis });
return;
}
if (active) {
sendJson(res, 200, { kind: 'active', game: active });
return;
}
sendJson(res, 404, { error: 'Game not found.' });
return;
}
}
sendJson(res, 404, { error: 'API route not found.' });
} catch (err) {
const status = (err as { statusCode?: number }).statusCode || 500;
const message = err instanceof Error ? err.message : 'Internal server error';
if (status >= 500) {
console.error('[HTTP Error]', err);
}
if (!res.headersSent) {
sendJson(res, status, { error: message });
}
}
};
}