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_with_id(engine_name, id) {
136 const engine = engines[engine_name];
138 const game = new engine(id);
140 this.games[id] = game;
145 create_game(engine_name) {
147 var id = this.generate_id();
148 } while (id in this.games);
150 return this.create_game_with_id(engine_name, id);
154 /* Some letters we don't use in our IDs:
156 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
157 * 2. Lowercase letters (replace with corresponding capital on input)
158 * 3. N (replace with M on input)
159 * 4. B (replace with P on input)
160 * 5. F,X (replace with S on input)
162 LMNO.letters = "CCDDDGGGHHJKLLLLMMMMPPPPQRRRSSSTTTVVWWYYZ";
164 const lmno = new LMNO();
166 /* Force a game ID into a canonical form as described above. */
167 function lmno_canonize(id) {
169 id = id.toUpperCase();
171 /* Replace unused letters with nearest phonetic match. */
172 id = id.replace(/N/g, 'M');
173 id = id.replace(/B/g, 'P');
174 id = id.replace(/F/g, 'S');
175 id = id.replace(/X/g, 'S');
177 /* Replace unused numbers nearest visual match. */
178 id = id.replace(/0/g, 'O');
179 id = id.replace(/1/g, 'I');
180 id = id.replace(/5/g, 'S');
185 app.post('/new/:game_engine', (request, response) => {
186 const game_engine = request.params.game_engine;
187 const game = lmno.create_game(game_engine);
188 response.send(JSON.stringify(game.id));
191 /* Redirect any requests to a game ID at the top-level.
193 * Specifically, after obtaining the game ID (from the path) we simply
194 * lookup the game engine for the corresponding game and then redirect
195 * to the engine- and game-specific path.
197 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
198 const game_id = request.path.replace(/\//g, "");
199 const canon_id = lmno_canonize(game_id);
201 /* Redirect user to page with the canonical ID in it. */
202 if (game_id !== canon_id) {
203 response.redirect(301, `/${canon_id}/`);
207 const game = lmno.games[game_id];
208 if (game === undefined) {
209 response.sendStatus(404);
212 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
215 /* LMNO middleware to lookup the game. */
216 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
217 const engine = request.params.engine;
218 const game_id = request.params.game_id;
219 const canon_id = lmno_canonize(game_id);
221 /* Redirect user to page with the canonical ID in it, also ensuring
222 * that the game ID is _always_ followed by a slash. */
223 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
224 if (game_id !== canon_id ||
225 ! has_slash.test(request.originalUrl))
227 const old_path = new RegExp(`/${engine}/${game_id}/?`);
228 const new_path = `/${engine}/${canon_id}/`;
229 const new_url = request.originalUrl.replace(old_path, new_path);
230 response.redirect(301, new_url);
234 /* See if there is any game with this ID. */
235 const game = lmno.games[game_id];
236 if (game === undefined) {
237 response.sendStatus(404);
241 /* Stash the game onto the request to be used by the game-specific code. */
246 function auth_admin(request, response, next) {
247 /* If there is no user associated with this session, redirect to the login
248 * page (and set a "next" query parameter so we can come back here).
250 if (! request.session.user) {
251 response.redirect(302, "/login?next=" + request.path);
255 /* If the user is logged in but not authorized to view the page then
256 * we return that error. */
257 if (request.session.user.role !== "admin") {
258 response.status(401).send("Unauthorized");
264 app.get('/logout', (request, response) => {
265 request.session.user = undefined;
266 request.session.destroy();
268 response.send("You are now logged out.");
271 app.get('/login', (request, response) => {
272 if (request.session.user) {
273 response.send("Welcome, " + request.session.user + ".");
277 response.render('login.html');
280 app.post('/login', async (request, response) => {
281 const username = request.body.username;
282 const password = request.body.password;
283 const user = lmno_config.users[username];
285 response.sendStatus(404);
288 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
290 response.sendStatus(404);
293 request.session.user = { username: user.username, role: user.role };
294 response.sendStatus(200);
298 /* API to set uer profile information */
299 app.put('/profile', (request, response) => {
300 const nickname = request.body.nickname;
302 request.session.nickname = nickname;
303 request.session.save();
308 /* An admin page (only available to admin users, of course) */
309 app.get('/admin/', auth_admin, (request, response) => {
313 for (let id in lmno.games) {
314 if (lmno.games[id].players.filter(p => p.active).length > 0)
315 active.push(lmno.games[id]);
317 idle.push(lmno.games[id]);
319 response.render('admin.html', { games: { active: active, idle: idle}});
323 /* Mount sub apps. only _after_ we have done all the middleware we need. */
324 for (let key in engines) {
325 const engine = engines[key];
326 const router = engine.router;
328 /* Add routes that are common to all games. */
329 router.get('/', (request, response) => {
330 const game = request.game;
332 if (! request.session.nickname) {
333 response.render('choose-nickname.html', {
334 game_name: game.meta.name,
335 options: game.meta.options
338 response.render(`${game.meta.identifier}-game.html`);
342 router.put('/player', (request, response) => {
343 const game = request.game;
345 game.handle_player(request, response);
348 router.get('/events', (request, response) => {
349 const game = request.game;
351 game.handle_events(request, response);
354 /* Further, add some routes conditionally depending on whether the
355 * engine provides specific, necessary methods for the routes. */
357 /* Note: We have to use hasOwnProperty here since the base Game
358 * class has a geeric add_move function, and we don't want that to
359 * have any influence on our decision. Only if the child has
360 * overridden that do we want to create a "/move" route. */
361 if (engine.prototype.hasOwnProperty("add_move")) {
362 router.post('/move', (request, response) => {
363 const game = request.game;
364 const move = request.body.move;
365 const player = game.players_by_session[request.session.id];
367 /* Reject move if there is no player for this session. */
369 response.json({legal: false, message: "No valid player from session"});
373 const result = game.add_move(player, move);
375 /* Take care of any generic post-move work. */
376 game.post_move(player, result);
378 /* Feed move response back to the client. */
379 response.json(result);
381 /* And only if legal, inform all clients. */
385 game.broadcast_move(move);
389 /* And mount the whole router at the path for the game. */
390 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
393 app.listen(4000, function () {
394 console.log('LMNO server listening on localhost:4000');