// Urali Chess Academy: the academy's own little back end (a stand-in for a real academy's system, e.g. MindMentorz). // It owns the student list, creates events on ChessRooq Arbiter through the API, hands each student their game link, // and receives results back by webhook. The Arbiter API key lives only here, never in a browser. // No dependencies: Node 18+ (http, fetch, crypto). import { createServer } from 'node:http'; import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; import { readFileSync, writeFileSync, existsSync, renameSync } from 'node:fs'; const PORT = Number(process.env.PORT ?? 3110); const API = process.env.ARBITER_API ?? 'https://sandbox.api.arbiter.chessrooq.com'; const KEY = process.env.ARBITER_KEY; const PUBLIC_URL = process.env.PUBLIC_URL ?? 'https://demo.chessrooq.com'; const DATA = process.env.DATA_FILE ?? new URL('./data.json', import.meta.url).pathname; if (!KEY) throw new Error('ARBITER_KEY is not set'); // ------------------------------------------------------------------ the academy's own data const STUDENTS = [ { id: 'URC-001', firstName: 'Aarav', lastName: 'Rao', rating: 1480, batch: 'Advanced' }, { id: 'URC-002', firstName: 'Diya', lastName: 'Menon', rating: 1410, batch: 'Advanced' }, { id: 'URC-003', firstName: 'Kabir', lastName: 'Shetty', rating: 1320, batch: 'Advanced' }, { id: 'URC-004', firstName: 'Meera', lastName: 'Iyer', rating: 1250, batch: 'Intermediate' }, { id: 'URC-005', firstName: 'Rohan', lastName: 'Gowda', rating: 1180, batch: 'Intermediate' }, { id: 'URC-006', firstName: 'Ananya', lastName: 'Kulkarni', rating: 1090, batch: 'Intermediate' }, { id: 'URC-007', firstName: 'Vihaan', lastName: 'Naik', rating: 960, batch: 'Beginners' }, { id: 'URC-008', firstName: 'Saanvi', lastName: 'Hegde', rating: 880, batch: 'Beginners' }, ]; const nameOf = (s) => `${s.firstName} ${s.lastName}`; const byId = new Map(STUDENTS.map((s) => [s.id, s])); const load = () => (existsSync(DATA) ? JSON.parse(readFileSync(DATA, 'utf8')) : {}); const db = Object.assign({ events: [], results: [], webhookSecret: null, cookieSecret: randomBytes(32).toString('hex') }, load()); const save = () => { writeFileSync(DATA + '.tmp', JSON.stringify(db, null, 1)); renameSync(DATA + '.tmp', DATA); }; save(); // ------------------------------------------------------------------ ChessRooq Arbiter API async function arbiter(method, path, body) { const r = await fetch(API + path, { method, headers: { authorization: `Bearer ${KEY}`, 'content-type': 'application/json', ...(method === 'POST' ? { 'idempotency-key': randomBytes(12).toString('hex') } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), }); const text = await r.text(); if (!r.ok) throw Object.assign(new Error(`Arbiter ${method} ${path}: ${r.status} ${text.slice(0, 300)}`), { status: r.status }); return text ? JSON.parse(text) : {}; } /** Students exist on Arbiter under the academy's own ids (ext:URC-001); safe to repeat. */ async function syncStudents() { for (const s of STUDENTS) await arbiter('PUT', `/v1/players/${s.id}`, { firstName: s.firstName, lastName: s.lastName, club: 'Urali Chess Academy' }); } /** Results come back to us: one webhook for the events we care about. */ async function ensureWebhook() { if (db.webhookSecret) return; const w = await arbiter('POST', '/v1/webhooks', { url: `${PUBLIC_URL}/app/api/webhooks/arbiter`, events: ['result.recorded', 'round.paired', 'tournament.completed'] }); db.webhookSecret = w.secret; save(); } async function createEvent({ name, students, rounds, minutes, increment, kind }) { const t = await arbiter('POST', '/v1/tournaments', { name, externalId: `urali-${Date.now().toString(36)}`, format: 'swiss', mode: 'online', maxPlayers: Math.max(4, students.length), roundsPlanned: rounds, baseSeconds: minutes * 60, incrementSeconds: increment, autoPairNextRound: true, secondsBetweenRounds: 30, }); await arbiter('POST', `/v1/tournaments/${t.id}/entries`, { entries: students.map((s) => ({ player: `ext:${s.id}`, rating: s.rating })) }); await arbiter('POST', `/v1/tournaments/${t.id}/start`); await arbiter('POST', `/v1/tournaments/${t.id}/rounds`); db.events.unshift({ id: t.id, code: t.code, name, kind, students: students.map((s) => s.id), createdAt: new Date().toISOString() }); db.events = db.events.slice(0, 30); save(); return { id: t.id, code: t.code, name }; } /** The newest running event this student plays in. */ async function currentEventFor(studentId) { for (const e of db.events.filter((x) => x.students.includes(studentId))) { const t = await arbiter('GET', `/v1/tournaments/${e.id}`).catch(() => null); if (t && t.status === 'in_progress') return { ...e, round: t.currentRound, rounds: t.roundsPlanned }; } return null; } // ------------------------------------------------------------------ demo sign-in (a signed cookie; a real academy uses its own login) const sign = (v) => `${v}.${createHmac('sha256', db.cookieSecret).update(v).digest('hex').slice(0, 32)}`; function studentFrom(req) { const c = Object.fromEntries((req.headers.cookie ?? '').split(';').map((p) => p.trim().split('=')).filter((p) => p.length === 2)); const raw = c.urali_student ? decodeURIComponent(c.urali_student) : ''; const id = raw.split('.')[0]; return raw && sign(id) === raw ? byId.get(id) : undefined; } function verifyWebhook(body, header) { if (!db.webhookSecret) return false; const parts = Object.fromEntries((header ?? '').split(',').map((p) => p.split('='))); const t = Number(parts.t); if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false; const expected = createHmac('sha256', db.webhookSecret).update(`${t}.${body}`).digest('hex'); return typeof parts.v1 === 'string' && parts.v1.length === expected.length && timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected)); } // ------------------------------------------------------------------ HTTP const json = (res, status, body, headers = {}) => { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers }); res.end(JSON.stringify(body)); }; const readBody = (req) => new Promise((resolve, reject) => { let b = ''; req.on('data', (c) => { b += c; if (b.length > 64_000) { reject(new Error('too big')); req.destroy(); } }); req.on('end', () => resolve(b)); }); const pick = (ids) => ids.map((id) => byId.get(id)).filter(Boolean); const routes = { 'GET /api/students': async () => STUDENTS.map((s) => ({ id: s.id, name: nameOf(s), rating: s.rating, batch: s.batch })), 'POST /api/session': async (req, res, body) => { const s = byId.get(JSON.parse(body || '{}').studentId); if (!s) return json(res, 400, { error: 'Pick a student.' }); json(res, 200, { id: s.id, name: nameOf(s) }, { 'set-cookie': `urali_student=${encodeURIComponent(sign(s.id))}; Path=/app/; HttpOnly; Secure; SameSite=Lax; Max-Age=28800` }); }, 'DELETE /api/session': async (req, res) => json(res, 200, {}, { 'set-cookie': 'urali_student=; Path=/app/; Max-Age=0' }), 'GET /api/me': async (req) => { const s = studentFrom(req); if (!s) return { student: null }; const e = await currentEventFor(s.id); return { student: { id: s.id, name: nameOf(s), rating: s.rating, batch: s.batch }, event: e && { name: e.name, code: e.code, round: e.round, rounds: e.rounds } }; }, /** Option 4: the student's game link, fetched server-side with the academy's key. */ 'POST /api/play-link': async (req, res) => { const s = studentFrom(req); if (!s) return json(res, 401, { error: 'Sign in first.' }); const e = await currentEventFor(s.id); if (!e) return json(res, 404, { error: 'No game for you right now. Ask your coach to start one.' }); const tok = await arbiter('POST', `/v1/tournaments/${e.id}/play-token`, { player: `ext:${s.id}` }); return { event: e.name, code: e.code, pageUrl: tok.pageUrl, url: tok.url, expiresAt: tok.expiresAt }; }, 'GET /api/events': async () => { const out = []; for (const e of db.events.slice(0, 10)) { const t = await arbiter('GET', `/v1/tournaments/${e.id}`).catch(() => null); if (t) out.push({ name: e.name, code: e.code, status: t.status, round: t.currentRound, rounds: t.roundsPlanned, createdAt: e.createdAt }); } return out; }, 'GET /api/results': async () => db.results.slice(0, 20), 'POST /api/webhooks/arbiter': async (req, res, body) => { if (!verifyWebhook(body, req.headers['x-arbiter-signature'])) return json(res, 400, { error: 'bad signature' }); const evt = JSON.parse(body); const ev = db.events.find((e) => e.id === evt.data?.tournamentId); db.results.unshift({ type: evt.type, at: evt.createdAt, event: ev?.name ?? 'An event', data: evt.data }); db.results = db.results.slice(0, 50); save(); return { ok: true }; }, // Coach actions (nginx asks for the coach password in front of /app/api/coach/) 'POST /api/coach/quick-game': async (req, res, body) => { const { white, black, minutes = 5, increment = 3 } = JSON.parse(body || '{}'); const [a, b] = pick([white, black]); if (!a || !b || a === b) return json(res, 400, { error: 'Pick two different students.' }); return createEvent({ name: `Quick game: ${a.firstName} vs ${b.firstName}`, students: [a, b], rounds: 1, minutes, increment, kind: 'quick' }); }, 'POST /api/coach/club-night': async (req, res, body) => { const { students: ids = [], rounds = 3, minutes = 5, increment = 3 } = JSON.parse(body || '{}'); const students = pick(ids); if (students.length < 2) return json(res, 400, { error: 'Pick at least two students.' }); const day = new Date().toLocaleDateString('en-IN', { weekday: 'long', timeZone: 'Asia/Kolkata' }); return createEvent({ name: `${day} Club Night`, students, rounds: Math.min(7, Math.max(1, rounds)), minutes, increment, kind: 'club' }); }, }; createServer(async (req, res) => { const path = (req.url ?? '').split('?')[0].replace(/^\/app/, ''); const handler = routes[`${req.method} ${path}`]; if (!handler) return json(res, 404, { error: 'Not found' }); try { const body = req.method === 'POST' || req.method === 'PUT' ? await readBody(req) : ''; const out = await handler(req, res, body); if (!res.headersSent && out !== undefined) json(res, 200, out); } catch (err) { console.error(err); if (!res.headersSent) json(res, err.status === 409 ? 409 : 502, { error: 'Something went wrong talking to ChessRooq. Try again.' }); } }).listen(PORT, '127.0.0.1', async () => { console.log(`urali academy app on 127.0.0.1:${PORT}`); try { await syncStudents(); await ensureWebhook(); console.log('students synced, webhook ready'); } catch (e) { console.error('startup sync failed (will still serve):', e.message); } });