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 nunjucks.configure("templates", {
58 /* Load each of our game mini-apps.
60 * Each "engine" we load here must have a property .Game on the
61 * exports object that should be a class that extends the common base
64 * In turn, each engine's Game must have the following properties:
66 * .meta: An object with .name and .identifier properties.
68 * Here, .name is a string giving a human-readable name
69 * for the game, such as "Tic Tac Toe" while .identifier
70 * is the short, single-word, all-lowercase identifier
71 * that is used in the path of the URL, such as
74 * .router: An express Router object
76 * Any game-specific routes should already be on the
77 * router. Then, LMNO will add common routes including:
79 * / Serves <identifier>-game.html template
81 * /player Allows client to set name or team
83 * /events Serves a stream of events. Game can override
84 * the handle_events method, call super() first,
85 * and then have code to add custom events.
87 * /moves Receives move data from clients. This route
88 * is only added if the Game class has an
92 empires: require("./empires").Game,
93 tictactoe: require("./tictactoe").Game,
94 scribe: require("./scribe").Game,
95 empathy: require("./empathy").Game
104 /* Note: The copy from Array(4) to [...Array(4)] is necessary so
105 * that map() will actually work, (which it doesn't on an array
106 * from Array(N) which is in this strange state of having "empty"
107 * items rather than "undefined" as we get after [...Array(4)] */
108 return [...Array(4)].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
111 create_game(engine_name) {
113 var id = this.generate_id();
114 } while (id in this.games);
116 const engine = engines[engine_name];
118 const game = new engine(id);
120 this.games[id] = game;
126 /* Some letters we don't use in our IDs:
128 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
129 * 2. Lowercase letters (replace with corresponding capital on input)
130 * 3. N (replace with M on input)
131 * 4. P (replace with B on input)
132 * 5. S (replace with F on input)
134 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
136 const lmno = new LMNO();
138 /* Force a game ID into a canonical form as described above. */
139 function lmno_canonize(id) {
141 id = id.toUpperCase();
143 /* Replace unused letters with nearest phonetic match. */
144 id = id.replace(/N/g, 'M');
145 id = id.replace(/P/g, 'B');
146 id = id.replace(/S/g, 'F');
148 /* Replace unused numbers nearest visual match. */
149 id = id.replace(/0/g, 'O');
150 id = id.replace(/1/g, 'I');
151 id = id.replace(/5/g, 'S');
156 app.post('/new/:game_engine', (request, response) => {
157 const game_engine = request.params.game_engine;
158 const game = lmno.create_game(game_engine);
159 response.send(JSON.stringify(game.id));
162 /* Redirect any requests to a game ID at the top-level.
164 * Specifically, after obtaining the game ID (from the path) we simply
165 * lookup the game engine for the corresponding game and then redirect
166 * to the engine- and game-specific path.
168 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
169 const game_id = request.path.replace(/\//g, "");
170 const canon_id = lmno_canonize(game_id);
172 /* Redirect user to page with the canonical ID in it. */
173 if (game_id !== canon_id) {
174 response.redirect(301, `/${canon_id}/`);
178 const game = lmno.games[game_id];
179 if (game === undefined) {
180 response.sendStatus(404);
183 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
186 /* LMNO middleware to lookup the game. */
187 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
188 const engine = request.params.engine;
189 const game_id = request.params.game_id;
190 const canon_id = lmno_canonize(game_id);
192 /* Redirect user to page with the canonical ID in it, also ensuring
193 * that the game ID is _always_ followed by a slash. */
194 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
195 if (game_id !== canon_id ||
196 ! has_slash.test(request.originalUrl))
198 const old_path = new RegExp(`/${engine}/${game_id}/?`);
199 const new_path = `/${engine}/${canon_id}/`;
200 const new_url = request.originalUrl.replace(old_path, new_path);
201 response.redirect(301, new_url);
205 /* See if there is any game with this ID. */
206 const game = lmno.games[game_id];
207 if (game === undefined) {
208 response.sendStatus(404);
212 /* Stash the game onto the request to be used by the game-specific code. */
217 function auth_admin(request, response, next) {
218 /* If there is no user associated with this session, redirect to the login
219 * page (and set a "next" query parameter so we can come back here).
221 if (! request.session.user) {
222 response.redirect(302, "/login?next=" + request.path);
226 /* If the user is logged in but not authorized to view the page then
227 * we return that error. */
228 if (request.session.user.role !== "admin") {
229 response.status(401).send("Unauthorized");
235 app.get('/logout', (request, response) => {
236 request.session.user = undefined;
237 request.session.destroy();
239 response.send("You are now logged out.");
242 app.get('/login', (request, response) => {
243 if (request.session.user) {
244 response.send("Welcome, " + request.session.user + ".");
248 response.render('login.html');
251 app.post('/login', async (request, response) => {
252 const username = request.body.username;
253 const password = request.body.password;
254 const user = lmno_config.users[username];
256 response.sendStatus(404);
259 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
261 response.sendStatus(404);
264 request.session.user = { username: user.username, role: user.role };
265 response.sendStatus(200);
269 /* API to set uer profile information */
270 app.put('/profile', (request, response) => {
271 const nickname = request.body.nickname;
273 request.session.nickname = nickname;
274 request.session.save();
279 /* An admin page (only available to admin users, of course) */
280 app.get('/admin/', auth_admin, (request, response) => {
284 for (let id in lmno.games) {
285 if (lmno.games[id].players.length)
286 active.push(lmno.games[id]);
288 idle.push(lmno.games[id]);
290 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
294 /* Mount sub apps. only _after_ we have done all the middleware we need. */
295 for (let key in engines) {
296 const engine = engines[key];
297 const router = engine.router;
299 /* Add routes that are common to all games. */
300 router.get('/', (request, response) => {
301 const game = request.game;
303 if (! request.session.nickname) {
304 response.render('choose-nickname.html', {
305 game_name: game.meta.name,
306 options: game.meta.options
309 response.render(`${game.meta.identifier}-game.html`);
313 router.put('/player', (request, response) => {
314 const game = request.game;
316 game.handle_player(request, response);
319 router.get('/events', (request, response) => {
320 const game = request.game;
322 game.handle_events(request, response);
325 /* Further, add some routes conditionally depending on whether the
326 * engine provides specific, necessary methods for the routes. */
328 /* Note: We have to use hasOwnProperty here since the base Game
329 * class has a geeric add_move function, and we don't want that to
330 * have any influence on our decision. Only if the child has
331 * overridden that do we want to create a "/move" route. */
332 if (engine.prototype.hasOwnProperty("add_move")) {
333 router.post('/move', (request, response) => {
334 const game = request.game;
335 const move = request.body.move;
336 const player = game.players_by_session[request.session.id];
338 /* Reject move if there is no player for this session. */
340 response.json({legal: false, message: "No valid player from session"});
344 const result = game.add_move(player, move);
346 /* Take care of any generic post-move work. */
347 game.post_move(player, result);
349 /* Feed move response back to the client. */
350 response.json(result);
352 /* And only if legal, inform all clients. */
356 game.broadcast_move(move);
360 /* And mount the whole router at the path for the game. */
361 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
364 app.listen(4000, function () {
365 console.log('LMNO server listening on localhost:4000');