NT-Connections/server.js
Aidan Dona b2f8e879ab Add puzzle hints and per-word descriptions with sources
Hint is revealed on demand below the board while playing. After the game
ends, each word's description and source link are listed below the
puzzle, and hovering a solved word highlights its entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:44:07 -05:00

139 lines
6.3 KiB
JavaScript

const path = require('node:path');
const fs = require('node:fs');
const crypto = require('node:crypto');
const { DatabaseSync } = require('node:sqlite');
const express = require('express');
const { validateGame, checkGuess, shuffle } = require('./lib');
const PORT = process.env.PORT || 3000;
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'data', 'games.db');
if (!ADMIN_PASSWORD) {
console.error('Set ADMIN_PASSWORD before starting the server.');
process.exit(1);
}
fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
const db = new DatabaseSync(DB_PATH);
db.exec(`CREATE TABLE IF NOT EXISTS games (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
date TEXT UNIQUE,
groups_json TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)`);
// Added after launch; existing databases get the column on first start.
if (!db.prepare('PRAGMA table_info(games)').all().some((c) => c.name === 'hint')) db.exec('ALTER TABLE games ADD COLUMN hint TEXT');
// Server's local date decides "today"; set TZ on the VPS to the timezone you want.
const today = () => new Date().toLocaleDateString('en-CA');
const toGame = (row) => row && { id: row.id, title: row.title, date: row.date, hint: row.hint || '', groups: JSON.parse(row.groups_json) };
// A game is public once its date has arrived (undated games are always public).
const getPublic = (id) =>
toGame(db.prepare('SELECT * FROM games WHERE id = ? AND (date IS NULL OR date <= ?)').get(Number(id), today()));
// Stateless session: the cookie is an HMAC of the password, so changing the password logs everyone out.
const SESSION = crypto.createHmac('sha256', ADMIN_PASSWORD).update('nt-admin-session').digest('hex');
const safeEqual = (a, b) => {
const x = crypto.createHash('sha256').update(String(a)).digest();
const y = crypto.createHash('sha256').update(String(b)).digest();
return crypto.timingSafeEqual(x, y);
};
const cookie = (req, name) =>
(req.headers.cookie || '').split(';').map((c) => c.trim().split('=')).find(([k]) => k === name)?.[1];
const isAdmin = (req) => safeEqual(cookie(req, 'nt_admin') || '', SESSION);
const requireAdmin = (req, res, next) => (isAdmin(req) ? next() : res.status(401).json({ error: 'Log in first.' }));
const app = express();
app.set('trust proxy', 'loopback'); // nginx on the same box
app.use(express.json());
app.use('/vendor/font', express.static(path.join(__dirname, 'node_modules/@fontsource/outfit')));
app.use('/vendor/icons', express.static(path.join(__dirname, 'node_modules/@phosphor-icons/web/src/bold')));
app.use(express.static(path.join(__dirname, 'public'), { index: false }));
const page = (file) => (req, res) => res.sendFile(path.join(__dirname, 'public', file));
app.get('/', page('play.html'));
app.get('/play/:id', page('play.html'));
app.get('/puzzles', page('puzzles.html'));
app.get('/admin', page('admin.html'));
// ---- Player API (never sends group membership until solved or revealed) ----
const publicView = (g) => ({ id: g.id, title: g.title, date: g.date, hint: g.hint, words: shuffle(g.groups.flatMap((x) => x.words)) });
app.get('/api/games', (req, res) => {
const rows = db
.prepare('SELECT id, title, date FROM games WHERE date IS NULL OR date <= ? ORDER BY date IS NULL, date DESC, id DESC')
.all(today());
res.json(rows);
});
app.get('/api/daily', (req, res) => {
const row = db.prepare('SELECT * FROM games WHERE date <= ? ORDER BY date DESC LIMIT 1').get(today());
if (!row) return res.status(404).json({ error: 'No puzzle scheduled yet.' });
res.json(publicView(toGame(row)));
});
app.get('/api/games/:id', (req, res) => {
const g = getPublic(req.params.id);
if (!g) return res.status(404).json({ error: 'Puzzle not found.' });
res.json(publicView(g));
});
app.post('/api/games/:id/guess', (req, res) => {
const g = getPublic(req.params.id);
if (!g) return res.status(404).json({ error: 'Puzzle not found.' });
const out = checkGuess(g.groups, req.body?.words);
res.status(out.error ? 400 : 200).json(out);
});
app.post('/api/games/:id/reveal', (req, res) => {
const g = getPublic(req.params.id);
if (!g) return res.status(404).json({ error: 'Puzzle not found.' });
res.json({ groups: g.groups });
});
// ---- Admin ----
app.post('/api/login', async (req, res) => {
if (!safeEqual(req.body?.password ?? '', ADMIN_PASSWORD)) {
await new Promise((r) => setTimeout(r, 1000)); // slow down guessing
return res.status(401).json({ error: 'Wrong password.' });
}
const secure = req.secure ? '; Secure' : '';
res.setHeader('Set-Cookie', `nt_admin=${SESSION}; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000${secure}`);
res.json({ ok: true });
});
app.post('/api/logout', (req, res) => {
res.setHeader('Set-Cookie', 'nt_admin=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');
res.json({ ok: true });
});
app.get('/api/admin/games', requireAdmin, (req, res) => {
res.json(db.prepare('SELECT * FROM games ORDER BY date IS NULL, date DESC, id DESC').all().map(toGame));
});
function save(req, res, id) {
const { errors, game } = validateGame(req.body);
if (errors) return res.status(400).json({ errors });
try {
const args = [game.title, game.date, game.hint || null, JSON.stringify(game.groups)];
const r = id
? db.prepare("UPDATE games SET title = ?, date = ?, hint = ?, groups_json = ?, updated_at = datetime('now') WHERE id = ?").run(...args, id)
: db.prepare('INSERT INTO games (title, date, hint, groups_json) VALUES (?, ?, ?, ?)').run(...args);
if (id && r.changes === 0) return res.status(404).json({ errors: ['Puzzle not found.'] });
res.json({ id: id || Number(r.lastInsertRowid) });
} catch (e) {
if (String(e.message).includes('UNIQUE')) return res.status(409).json({ errors: [`Another puzzle already uses ${game.date}.`] });
throw e;
}
}
app.post('/api/admin/games', requireAdmin, (req, res) => save(req, res, null));
app.put('/api/admin/games/:id', requireAdmin, (req, res) => save(req, res, Number(req.params.id)));
app.delete('/api/admin/games/:id', requireAdmin, (req, res) => {
db.prepare('DELETE FROM games WHERE id = ?').run(Number(req.params.id));
res.json({ ok: true });
});
app.listen(PORT, '127.0.0.1', () => console.log(`NT Connections on http://localhost:${PORT}`));