1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
4 const session = require("express-session");
5 const bcrypt = require("bcrypt");
6 const path = require("path");
7 const nunjucks = require("nunjucks");
10 var lmno_config = require("./lmno-config.json");
16 function config_usage() {
17 console.log(`Error: Refusing to run without configuration.
19 Please create a file named lmno-config.json that looks as follows:
22 "session_secret": "<this should be a long string of true-random characters>",
24 "username": "<username>",
25 "password_hash_bcrypt": "<password_hash_made_by_bcrypt>"
29 Note: Of course, change all of <these-parts> to actual values desired.
31 The "node lmno-passwd.js" command can help generate password hashes.`);
34 const app = express();
36 /* This 'trust proxy' option, (and, really? a space in an option
37 * name?!) means that express will grab hostname and IP values from
38 * the X-Forwarded-* header fields. We need that so that our games
39 * will display a proper hostname of https://lmno.games/WXYZ instead
40 * of http://localhost/QFBL which will obviously not be a helpful
41 * thing to share around.
43 app.set('trust proxy', true);
45 app.use(body_parser.urlencoded({ extended: false }));
46 app.use(body_parser.json());
48 secret: lmno_config.session_secret,
50 saveUninitialized: false
53 const njx = nunjucks.configure("templates", {
58 njx.addFilter('active', function(list) {
60 return list.filter(e => e.active === true);
65 njx.addFilter('idle', function(list) {
67 return list.filter(e => e.active === false);
72 njx.addFilter('map_prop', function(list, prop) {
74 return list.map(e => e[prop]);
79 /* Load each of our game mini-apps.
81 * Each "engine" we load here must have a property .Game on the
82 * exports object that should be a class that extends the common base
85 * In turn, each engine's Game must have the following properties:
87 * .meta: An object with .name and .identifier properties.
89 * Here, .name is a string giving a human-readable name
90 * for the game, such as "Tic Tac Toe" while .identifier
91 * is the short, single-word, all-lowercase identifier
92 * that is used in the path of the URL, such as
95 * .router: An express Router object
97 * Any game-specific routes should already be on the
98 * router. Then, LMNO will add common routes including:
100 * / Serves <identifier>-game.html template
102 * /player Allows client to set name or team
104 * /events Serves a stream of events. Game can override
105 * the handle_events method, call super() first,
106 * and then have code to add custom events.
108 * /moves Receives move data from clients. This route
109 * is only added if the Game class has an
113 empires: require("./empires").Game,
114 tictactoe: require("./tictactoe").Game,
115 scribe: require("./scribe").Game,
116 empathy: require("./empathy").Game
125 /* Note: The copy from Array(4) to [...Array(4)] is necessary so
126 * that map() will actually work, (which it doesn't on an array
127 * from Array(N) which is in this strange state of having "empty"
128 * items rather than "undefined" as we get after [...Array(4)] */
129 return [...Array(4)].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
132 create_game(engine_name) {
134 var id = this.generate_id();
135 } while (id in this.games);
137 const engine = engines[engine_name];
139 const game = new engine(id);
141 this.games[id] = game;
147 /* Some letters we don't use in our IDs:
149 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
150 * 2. Lowercase letters (replace with corresponding capital on input)
151 * 3. N (replace with M on input)
152 * 4. B (replace with P on input)
153 * 5. F,X (replace with S on input)
155 LMNO.letters = "CCDDDGGGHHJKLLLLMMMMPPPPQRRRSSSTTTVVWWYYZ";
157 const lmno = new LMNO();
159 /* Force a game ID into a canonical form as described above. */
160 function lmno_canonize(id) {
162 id = id.toUpperCase();
164 /* Replace unused letters with nearest phonetic match. */
165 id = id.replace(/N/g, 'M');
166 id = id.replace(/B/g, 'P');
167 id = id.replace(/F/g, 'S');
168 id = id.replace(/X/g, 'S');
170 /* Replace unused numbers nearest visual match. */
171 id = id.replace(/0/g, 'O');
172 id = id.replace(/1/g, 'I');
173 id = id.replace(/5/g, 'S');
178 app.post('/new/:game_engine', (request, response) => {
179 const game_engine = request.params.game_engine;
180 const game = lmno.create_game(game_engine);
181 response.send(JSON.stringify(game.id));
184 /* Redirect any requests to a game ID at the top-level.
186 * Specifically, after obtaining the game ID (from the path) we simply
187 * lookup the game engine for the corresponding game and then redirect
188 * to the engine- and game-specific path.
190 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
191 const game_id = request.path.replace(/\//g, "");
192 const canon_id = lmno_canonize(game_id);
194 /* Redirect user to page with the canonical ID in it. */
195 if (game_id !== canon_id) {
196 response.redirect(301, `/${canon_id}/`);
200 const game = lmno.games[game_id];
201 if (game === undefined) {
202 response.sendStatus(404);
205 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
208 /* LMNO middleware to lookup the game. */
209 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
210 const engine = request.params.engine;
211 const game_id = request.params.game_id;
212 const canon_id = lmno_canonize(game_id);
214 /* Redirect user to page with the canonical ID in it, also ensuring
215 * that the game ID is _always_ followed by a slash. */
216 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
217 if (game_id !== canon_id ||
218 ! has_slash.test(request.originalUrl))
220 const old_path = new RegExp(`/${engine}/${game_id}/?`);
221 const new_path = `/${engine}/${canon_id}/`;
222 const new_url = request.originalUrl.replace(old_path, new_path);
223 response.redirect(301, new_url);
227 /* See if there is any game with this ID. */
228 const game = lmno.games[game_id];
229 if (game === undefined) {
230 response.sendStatus(404);
234 /* Stash the game onto the request to be used by the game-specific code. */
239 function auth_admin(request, response, next) {
240 /* If there is no user associated with this session, redirect to the login
241 * page (and set a "next" query parameter so we can come back here).
243 if (! request.session.user) {
244 response.redirect(302, "/login?next=" + request.path);
248 /* If the user is logged in but not authorized to view the page then
249 * we return that error. */
250 if (request.session.user.role !== "admin") {
251 response.status(401).send("Unauthorized");
257 app.get('/logout', (request, response) => {
258 request.session.user = undefined;
259 request.session.destroy();
261 response.send("You are now logged out.");
264 app.get('/login', (request, response) => {
265 if (request.session.user) {
266 response.send("Welcome, " + request.session.user + ".");
270 response.render('login.html');
273 app.post('/login', async (request, response) => {
274 const username = request.body.username;
275 const password = request.body.password;
276 const user = lmno_config.users[username];
278 response.sendStatus(404);
281 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
283 response.sendStatus(404);
286 request.session.user = { username: user.username, role: user.role };
287 response.sendStatus(200);
291 /* API to set uer profile information */
292 app.put('/profile', (request, response) => {
293 const nickname = request.body.nickname;
295 request.session.nickname = nickname;
296 request.session.save();
301 /* An admin page (only available to admin users, of course) */
302 app.get('/admin/', auth_admin, (request, response) => {
306 for (let id in lmno.games) {
307 if (lmno.games[id].players.filter(p => p.active).length > 0)
308 active.push(lmno.games[id]);
310 idle.push(lmno.games[id]);
312 response.render('admin.html', { games: { active: active, idle: idle}});
316 /* Mount sub apps. only _after_ we have done all the middleware we need. */
317 for (let key in engines) {
318 const engine = engines[key];
319 const router = engine.router;
321 /* Add routes that are common to all games. */
322 router.get('/', (request, response) => {
323 const game = request.game;
325 if (! request.session.nickname) {
326 response.render('choose-nickname.html', {
327 game_name: game.meta.name,
328 options: game.meta.options
331 response.render(`${game.meta.identifier}-game.html`);
335 router.put('/player', (request, response) => {
336 const game = request.game;
338 game.handle_player(request, response);
341 router.get('/events', (request, response) => {
342 const game = request.game;
344 game.handle_events(request, response);
347 /* Further, add some routes conditionally depending on whether the
348 * engine provides specific, necessary methods for the routes. */
350 /* Note: We have to use hasOwnProperty here since the base Game
351 * class has a geeric add_move function, and we don't want that to
352 * have any influence on our decision. Only if the child has
353 * overridden that do we want to create a "/move" route. */
354 if (engine.prototype.hasOwnProperty("add_move")) {
355 router.post('/move', (request, response) => {
356 const game = request.game;
357 const move = request.body.move;
358 const player = game.players_by_session[request.session.id];
360 /* Reject move if there is no player for this session. */
362 response.json({legal: false, message: "No valid player from session"});
366 const result = game.add_move(player, move);
368 /* Take care of any generic post-move work. */
369 game.post_move(player, result);
371 /* Feed move response back to the client. */
372 response.json(result);
374 /* And only if legal, inform all clients. */
378 game.broadcast_move(move);
382 /* And mount the whole router at the path for the game. */
383 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
386 app.listen(4000, function () {
387 console.log('LMNO server listening on localhost:4000');