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 /* Pre-allocate an empires game with ID QRST.
167 * This is for convenience in the development of the flempires
168 * client which would like to have stable API endpoints across
171 lmno.create_game_with_id("empires", "QRST");
173 /* Force a game ID into a canonical form as described above. */
174 function lmno_canonize(id) {
176 id = id.toUpperCase();
178 /* Replace unused letters with nearest phonetic match. */
179 id = id.replace(/N/g, 'M');
180 id = id.replace(/B/g, 'P');
181 id = id.replace(/F/g, 'S');
182 id = id.replace(/X/g, 'S');
184 /* Replace unused numbers nearest visual match. */
185 id = id.replace(/0/g, 'O');
186 id = id.replace(/1/g, 'I');
187 id = id.replace(/5/g, 'S');
192 app.post('/new/:game_engine', (request, response) => {
193 const game_engine = request.params.game_engine;
194 const game = lmno.create_game(game_engine);
195 response.send(JSON.stringify(game.id));
198 /* Redirect any requests to a game ID at the top-level.
200 * Specifically, after obtaining the game ID (from the path) we simply
201 * lookup the game engine for the corresponding game and then redirect
202 * to the engine- and game-specific path.
204 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
205 const game_id = request.path.replace(/\//g, "");
206 const canon_id = lmno_canonize(game_id);
208 /* Redirect user to page with the canonical ID in it. */
209 if (game_id !== canon_id) {
210 response.redirect(301, `/${canon_id}/`);
214 const game = lmno.games[game_id];
215 if (game === undefined) {
216 response.sendStatus(404);
219 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
222 /* LMNO middleware to lookup the game. */
223 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
224 const engine = request.params.engine;
225 const game_id = request.params.game_id;
226 const canon_id = lmno_canonize(game_id);
228 /* Redirect user to page with the canonical ID in it, also ensuring
229 * that the game ID is _always_ followed by a slash. */
230 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
231 if (game_id !== canon_id ||
232 ! has_slash.test(request.originalUrl))
234 const old_path = new RegExp(`/${engine}/${game_id}/?`);
235 const new_path = `/${engine}/${canon_id}/`;
236 const new_url = request.originalUrl.replace(old_path, new_path);
237 response.redirect(301, new_url);
241 /* See if there is any game with this ID. */
242 const game = lmno.games[game_id];
243 if (game === undefined) {
244 response.sendStatus(404);
248 /* Stash the game onto the request to be used by the game-specific code. */
253 function auth_admin(request, response, next) {
254 /* If there is no user associated with this session, redirect to the login
255 * page (and set a "next" query parameter so we can come back here).
257 if (! request.session.user) {
258 response.redirect(302, "/login?next=" + request.path);
262 /* If the user is logged in but not authorized to view the page then
263 * we return that error. */
264 if (request.session.user.role !== "admin") {
265 response.status(401).send("Unauthorized");
271 app.get('/logout', (request, response) => {
272 request.session.user = undefined;
273 request.session.destroy();
275 response.send("You are now logged out.");
278 app.get('/login', (request, response) => {
279 if (request.session.user) {
280 response.send("Welcome, " + request.session.user + ".");
284 response.render('login.html');
287 app.post('/login', async (request, response) => {
288 const username = request.body.username;
289 const password = request.body.password;
290 const user = lmno_config.users[username];
292 response.sendStatus(404);
295 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
297 response.sendStatus(404);
300 request.session.user = { username: user.username, role: user.role };
301 response.sendStatus(200);
305 /* API to set uer profile information */
306 app.put('/profile', (request, response) => {
307 const nickname = request.body.nickname;
309 request.session.nickname = nickname;
310 request.session.save();
315 /* An admin page (only available to admin users, of course) */
316 app.get('/admin/', auth_admin, (request, response) => {
320 for (let id in lmno.games) {
321 if (lmno.games[id].players.filter(p => p.active).length > 0)
322 active.push(lmno.games[id]);
324 idle.push(lmno.games[id]);
326 response.render('admin.html', { games: { active: active, idle: idle}});
330 /* Mount sub apps. only _after_ we have done all the middleware we need. */
331 for (let key in engines) {
332 const engine = engines[key];
333 const router = engine.router;
335 /* Add routes that are common to all games. */
336 router.get('/', (request, response) => {
337 const game = request.game;
339 if (! request.session.nickname) {
340 response.render('choose-nickname.html', {
341 game_name: game.meta.name,
342 options: game.meta.options
345 response.render(`${game.meta.identifier}-game.html`);
349 router.put('/player', (request, response) => {
350 const game = request.game;
352 game.handle_player(request, response);
355 router.get('/events', (request, response) => {
356 const game = request.game;
358 game.handle_events(request, response);
361 /* Further, add some routes conditionally depending on whether the
362 * engine provides specific, necessary methods for the routes. */
364 /* Note: We have to use hasOwnProperty here since the base Game
365 * class has a geeric add_move function, and we don't want that to
366 * have any influence on our decision. Only if the child has
367 * overridden that do we want to create a "/move" route. */
368 if (engine.prototype.hasOwnProperty("add_move")) {
369 router.post('/move', (request, response) => {
370 const game = request.game;
371 const move = request.body.move;
372 const player = game.players_by_session[request.session.id];
374 /* Reject move if there is no player for this session. */
376 response.json({legal: false, message: "No valid player from session"});
380 const result = game.add_move(player, move);
382 /* Take care of any generic post-move work. */
383 game.post_move(player, result);
385 /* Feed move response back to the client. */
386 response.json(result);
388 /* And only if legal, inform all clients. */
392 game.broadcast_move(move);
396 /* And mount the whole router at the path for the game. */
397 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
400 app.listen(4000, function () {
401 console.log('LMNO server listening on localhost:4000');