Add Connections-style word game with puzzle editor
Express + node:sqlite server, vanilla HTML/JS frontend. Daily puzzle by assigned date, puzzle list, shuffle, one-away hint, shareable emoji results, and a password-protected admin page to create and edit puzzles. Answers are checked server-side and never sent before they are solved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0d3181ec99
commit
4a2309b589
18 changed files with 4286 additions and 0 deletions
137
server.js
Normal file
137
server.js
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
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'))
|
||||
)`);
|
||||
|
||||
// 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, 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, 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, JSON.stringify(game.groups)];
|
||||
const r = id
|
||||
? db.prepare("UPDATE games SET title = ?, date = ?, groups_json = ?, updated_at = datetime('now') WHERE id = ?").run(...args, id)
|
||||
: db.prepare('INSERT INTO games (title, date, 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}`));
|
||||
Loading…
Add table
Add a link
Reference in a new issue