Implement ChessUp server, vanilla TS UI, Stockfish analytics, and Docker/Cloudflared setup

This commit is contained in:
tyuXX 2026-11-22 18:18:15 +03:00
commit e2e085b341
52 changed files with 15730 additions and 0 deletions

420
tests/server.test.ts Normal file
View file

@ -0,0 +1,420 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import WebSocket from 'ws';
import { createApp, type ChessUpApp } from '../src/server/app';
import type { ActiveGameState, GameAnalysisReport, ServerWsMessage } from '../src/shared/types';
class TestClient {
public cookie = '';
public ws: WebSocket | null = null;
private msgQueue: ServerWsMessage[] = [];
private waiters: Array<{
pred: (m: ServerWsMessage) => boolean;
resolve: (m: ServerWsMessage) => void;
reject: (err: Error) => void;
timer: NodeJS.Timeout;
}> = [];
constructor(private readonly baseUrl: string) {}
async req<T>(urlPath: string, init: RequestInit = {}): Promise<{ status: number; data: T; rawText: string }> {
const headers: Record<string, string> = {};
if (init.body) headers['Content-Type'] = 'application/json';
if (this.cookie) headers['Cookie'] = this.cookie;
const resp = await fetch(this.baseUrl + urlPath, {
...init,
headers: {
...headers,
...(init.headers as Record<string, string> | undefined)
}
});
const setCookie = resp.headers.get('set-cookie');
if (setCookie) {
const part = setCookie.split(';')[0]!;
if (part.endsWith('=')) {
this.cookie = '';
} else {
this.cookie = part;
}
}
const rawText = await resp.text();
let data: unknown = {};
try {
data = rawText ? JSON.parse(rawText) : {};
} catch {
data = rawText;
}
return { status: resp.status, data: data as T, rawText };
}
connectWs(): Promise<void> {
return new Promise((resolve, reject) => {
const wsUrl = this.baseUrl.replace(/^http/, 'ws') + '/ws';
const headers: Record<string, string> = {};
if (this.cookie) headers['Cookie'] = this.cookie;
const ws = new WebSocket(wsUrl, { headers });
this.ws = ws;
ws.once('open', () => resolve());
ws.once('error', reject);
ws.on('message', (buf) => {
const msg = JSON.parse(buf.toString()) as ServerWsMessage;
for (let i = 0; i < this.waiters.length; i++) {
const w = this.waiters[i]!;
if (w.pred(msg)) {
this.waiters.splice(i, 1);
clearTimeout(w.timer);
w.resolve(msg);
return;
}
}
this.msgQueue.push(msg);
});
});
}
sendWs(msg: unknown): void {
assert.ok(this.ws && this.ws.readyState === WebSocket.OPEN, 'WS is not open');
this.ws.send(JSON.stringify(msg));
}
waitFor(pred: (m: ServerWsMessage) => boolean, timeoutMs: number = 8000): Promise<ServerWsMessage> {
for (let i = 0; i < this.msgQueue.length; i++) {
const m = this.msgQueue[i]!;
if (pred(m)) {
this.msgQueue.splice(i, 1);
return Promise.resolve(m);
}
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
const idx = this.waiters.findIndex((w) => w.timer === timer);
if (idx >= 0) this.waiters.splice(idx, 1);
reject(new Error('Timed out waiting for WS message'));
}, timeoutMs);
this.waiters.push({ pred, resolve, reject, timer });
});
}
closeWs(): Promise<void> {
return new Promise((resolve) => {
if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
this.ws = null;
resolve();
return;
}
this.ws.once('close', () => {
this.ws = null;
resolve();
});
this.ws.close();
});
}
}
test('ChessUp full server E2E: auth, lobby, PvP, Glicko-2, Stockfish analysis, bots, friends, invites, spectating, disconnect forfeit', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chessup-test-'));
const dbPath = path.join(tmpDir, 'test.db');
const app: ChessUpApp = createApp({
port: 0,
host: '127.0.0.1',
dbPath,
stockfishWorkers: 2,
analysisDepth: 8,
disconnectForfeitMs: 450,
disableRateLimit: true
});
const port = await app.start();
const baseUrl = `http://127.0.0.1:${port}`;
const alice = new TestClient(baseUrl);
const bob = new TestClient(baseUrl);
const spectator = new TestClient(baseUrl);
try {
// 1. Auth: register, duplicate check, login, password update
const regA = await alice.req<{ user: { id: number; username: string } }>('/api/auth/register', {
method: 'POST',
body: JSON.stringify({ username: 'Alice_01', password: 'password123' })
});
assert.equal(regA.status, 201);
assert.equal(regA.data.user.username, 'Alice_01');
const dupA = await alice.req('/api/auth/register', {
method: 'POST',
body: JSON.stringify({ username: 'alice_01', password: 'password123' })
});
assert.equal(dupA.status, 409);
const regB = await bob.req<{ user: { id: number; username: string } }>('/api/auth/register', {
method: 'POST',
body: JSON.stringify({ username: 'Bob_02', password: 'password456' })
});
assert.equal(regB.status, 201);
const badLogin = await new TestClient(baseUrl).req('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ username: 'Bob_02', password: 'wrong' })
});
assert.equal(badLogin.status, 401);
const meA = await alice.req<{ user: { username: string } | null }>('/api/auth/me');
assert.equal(meA.status, 200);
assert.equal(meA.data.user?.username, 'Alice_01');
// Connect WS clients
await alice.connectWs();
await bob.connectWs();
await spectator.connectWs();
await alice.waitFor((m) => m.type === 'session:init');
await bob.waitFor((m) => m.type === 'session:init');
await spectator.waitFor((m) => m.type === 'session:init');
// 2. Open lobby seek -> accept -> Scholar's Mate -> DB persistence + Glicko-2 update
alice.sendWs({ type: 'lobby:subscribe' });
bob.sendWs({ type: 'lobby:subscribe' });
await alice.waitFor((m) => m.type === 'lobby:state');
await bob.waitFor((m) => m.type === 'lobby:state');
alice.sendWs({
type: 'lobby:seek',
initialMs: 180_000,
incrementMs: 0,
rated: true,
colorPref: 'white'
});
const seekMsg = (await bob.waitFor(
(m) => m.type === 'lobby:state' && m.seeks.length === 1
)) as Extract<ServerWsMessage, { type: 'lobby:state' }>;
const seekId = seekMsg.seeks[0]!.id;
bob.sendWs({ type: 'lobby:accept_seek', seekId });
const startA = (await alice.waitFor((m) => m.type === 'game:started')) as Extract<
ServerWsMessage,
{ type: 'game:started' }
>;
const startB = (await bob.waitFor((m) => m.type === 'game:started')) as Extract<
ServerWsMessage,
{ type: 'game:started' }
>;
assert.equal(startA.gameId, startB.gameId);
const pvpGameId = startA.gameId;
alice.sendWs({ type: 'game:subscribe', gameId: pvpGameId });
bob.sendWs({ type: 'game:subscribe', gameId: pvpGameId });
spectator.sendWs({ type: 'game:subscribe', gameId: pvpGameId });
const stateA = (await alice.waitFor((m) => m.type === 'game:state')) as Extract<
ServerWsMessage,
{ type: 'game:state' }
>;
assert.equal(stateA.game.white.username, 'Alice_01');
assert.equal(stateA.game.black.username, 'Bob_02');
// Unauthenticated spectator watches + authenticated player chats
await spectator.waitFor((m) => m.type === 'game:state');
alice.sendWs({ type: 'game:chat', gameId: pvpGameId, text: 'Good luck!' });
const chatSpec = (await spectator.waitFor((m) => m.type === 'game:chat')) as Extract<
ServerWsMessage,
{ type: 'game:chat' }
>;
assert.equal(chatSpec.message.text, 'Good luck!');
// Play Scholar's Mate
const scholarMoves: Array<[TestClient, string]> = [
[alice, 'e2e4'],
[bob, 'e7e5'],
[alice, 'd1h5'],
[bob, 'b8c6'],
[alice, 'f1c4'],
[bob, 'g8f6'],
[alice, 'h5f7']
];
for (const [player, uci] of scholarMoves) {
player.sendWs({ type: 'game:move', gameId: pvpGameId, uci });
await alice.waitFor((m) => m.type === 'game:move' && m.uci === uci);
await bob.waitFor((m) => m.type === 'game:move' && m.uci === uci);
}
const overA = (await alice.waitFor((m) => m.type === 'game:over')) as Extract<
ServerWsMessage,
{ type: 'game:over' }
>;
assert.equal(overA.result, '1-0');
assert.equal(overA.termination, 'checkmate');
assert.equal(overA.saved, true);
assert.ok(overA.whiteRatingDiff !== null && overA.whiteRatingDiff > 0);
assert.ok(overA.blackRatingDiff !== null && overA.blackRatingDiff < 0);
// Check REST history, PGN, leaderboard
const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`);
assert.equal(storedRes.status, 200);
assert.equal(storedRes.data.game.result, '1-0');
const pgnRes = await alice.req<string>(`/api/games/${pvpGameId}/pgn`);
assert.equal(pgnRes.status, 200);
assert.ok(pgnRes.rawText.includes('Qxf7#'));
const lbRes = await alice.req<{ entries: Array<{ username: string }> }>('/api/leaderboard?category=blitz');
assert.equal(lbRes.status, 200);
assert.equal(lbRes.data.entries[0]!.username, 'Alice_01');
// 3. Stockfish Post-Game Analysis + Cache verification
alice.sendWs({ type: 'analysis:subscribe', gameId: pvpGameId });
const triggerRes = await alice.req<{ report: GameAnalysisReport }>(`/api/games/${pvpGameId}/analysis`, {
method: 'POST',
body: JSON.stringify({})
});
assert.ok(triggerRes.status === 202 || triggerRes.status === 200);
const analysisDone = (await alice.waitFor(
(m) => m.type === 'analysis:done' && m.gameId === pvpGameId,
15_000
)) as Extract<ServerWsMessage, { type: 'analysis:done' }>;
assert.equal(analysisDone.report.status, 'done');
assert.equal(analysisDone.report.plies.length, 7);
assert.equal(analysisDone.report.plies[5]!.classification, 'blunder');
// Second POST returns cached 200 immediately
const cachedRes = await alice.req<{ report: GameAnalysisReport }>(`/api/games/${pvpGameId}/analysis`, {
method: 'POST',
body: JSON.stringify({})
});
assert.equal(cachedRes.status, 200);
assert.equal(cachedRes.data.report.status, 'done');
// 4. Play vs Stockfish Level 1 + takeback
const botRes = await alice.req<{ gameId: string }>('/api/games/bot', {
method: 'POST',
body: JSON.stringify({ level: 1, colorPref: 'white', initialMs: 0, incrementMs: 0 })
});
assert.equal(botRes.status, 201);
const botGameId = botRes.data.gameId;
alice.sendWs({ type: 'game:subscribe', gameId: botGameId });
await alice.waitFor((m) => m.type === 'game:state' && m.game.id === botGameId);
alice.sendWs({ type: 'game:move', gameId: botGameId, uci: 'e2e4' });
await alice.waitFor((m) => m.type === 'game:move' && m.gameId === botGameId && m.uci === 'e2e4');
// Wait for Stockfish Level 1 response
await alice.waitFor((m) => m.type === 'game:move' && m.gameId === botGameId && m.turn === 'w');
// Takeback restores back to 0 plies
alice.sendWs({ type: 'game:takeback_offer', gameId: botGameId });
const tbMsg = (await alice.waitFor(
(m) => m.type === 'game:takeback' && m.gameId === botGameId
)) as Extract<ServerWsMessage, { type: 'game:takeback' }>;
assert.equal(tbMsg.game.movesUci.length, 0);
alice.sendWs({ type: 'game:abort', gameId: botGameId });
await alice.waitFor((m) => m.type === 'game:over' && m.gameId === botGameId && m.termination === 'aborted');
// 5. Mutual friends + Direct challenge
const frReq = await alice.req('/api/friends/request', {
method: 'POST',
body: JSON.stringify({ username: 'Bob_02' })
});
assert.equal(frReq.status, 200);
const frAcc = await bob.req('/api/friends/respond', {
method: 'POST',
body: JSON.stringify({ userId: regA.data.user.id, accept: true })
});
assert.equal(frAcc.status, 200);
alice.sendWs({
type: 'challenge:send',
toUserId: regB.data.user.id,
initialMs: 300_000,
incrementMs: 0,
rated: false,
colorPref: 'white'
});
const chalRecv = (await bob.waitFor((m) => m.type === 'challenge:received')) as Extract<
ServerWsMessage,
{ type: 'challenge:received' }
>;
bob.sendWs({ type: 'challenge:respond', challengeId: chalRecv.challenge.id, accept: true });
const chalStart = (await bob.waitFor(
(m) => m.type === 'game:started' && m.gameId !== pvpGameId
)) as Extract<ServerWsMessage, { type: 'game:started' }>;
const chalGameId = chalStart.gameId;
alice.sendWs({ type: 'game:subscribe', gameId: chalGameId });
bob.sendWs({ type: 'game:subscribe', gameId: chalGameId });
await alice.waitFor((m) => m.type === 'game:state' && m.game.id === chalGameId);
await bob.waitFor((m) => m.type === 'game:state' && m.game.id === chalGameId);
// Play 2 plies so game counts and test disconnect forfeit
alice.sendWs({ type: 'game:move', gameId: chalGameId, uci: 'd2d4' });
await bob.waitFor((m) => m.type === 'game:move' && m.gameId === chalGameId && m.uci === 'd2d4');
bob.sendWs({ type: 'game:move', gameId: chalGameId, uci: 'd7d5' });
await bob.waitFor((m) => m.type === 'game:move' && m.gameId === chalGameId && m.uci === 'd7d5');
// Alice disconnects -> after disconnectForfeitMs (450ms), Bob wins by abandonment!
await alice.closeWs();
const abandonOver = (await bob.waitFor(
(m) => m.type === 'game:over' && m.gameId === chalGameId
)) as Extract<ServerWsMessage, { type: 'game:over' }>;
assert.equal(abandonOver.result, '0-1');
assert.equal(abandonOver.termination, 'abandonment');
// 6. Shareable invite link flow
await alice.connectWs();
await alice.waitFor((m) => m.type === 'session:init');
const invCreate = await alice.req<{ invite: { token: string } }>('/api/invites', {
method: 'POST',
body: JSON.stringify({ initialMs: 600_000, incrementMs: 5_000, rated: false, colorPref: 'black' })
});
assert.equal(invCreate.status, 201);
const invToken = invCreate.data.invite.token;
const invGet = await bob.req<{ invite: { creatorUsername: string } }>(`/api/invites/${invToken}`);
assert.equal(invGet.status, 200);
assert.equal(invGet.data.invite.creatorUsername, 'Alice_01');
const invAcc = await bob.req<{ gameId: string }>(`/api/invites/${invToken}/accept`, { method: 'POST' });
assert.equal(invAcc.status, 200);
const invGame = await bob.req<{ kind: string; game: ActiveGameState }>(`/api/games/${invAcc.data.gameId}`);
assert.equal(invGame.status, 200);
assert.equal(invGame.data.game.white.username, 'Bob_02');
assert.equal(invGame.data.game.black.username, 'Alice_01');
// 7. Health endpoint, malformed URL handling, and X-Forwarded-Host origin support
const healthRes = await alice.req<{ ok: boolean }>('/api/health');
assert.equal(healthRes.status, 200);
assert.equal(healthRes.data.ok, true);
const badPathRes = await alice.req<{ error: string }>('/api/%E0%A4%A');
assert.equal(badPathRes.status, 400);
const fwdOriginRes = await new TestClient(baseUrl).req('/api/auth/logout', {
method: 'POST',
headers: { Origin: 'https://chess.example.com', 'X-Forwarded-Host': 'chess.example.com' }
});
assert.equal(fwdOriginRes.status, 200);
const badOriginPost = await alice.req('/api/auth/logout', {
method: 'POST',
headers: { Origin: 'https://evil.example.com', 'X-Forwarded-Host': 'chess.example.com' }
});
assert.equal(badOriginPost.status, 403);
} finally {
await alice.closeWs();
await bob.closeWs();
await spectator.closeWs();
await app.stop();
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});