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
103 return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
106 create_game(engine_name) {
108 var id = this.generate_id();
109 } while (id in this.games);
111 const engine = engines[engine_name];
113 const game = new engine(id);
115 this.games[id] = game;
121 /* Some letters we don't use in our IDs:
123 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
124 * 2. Lowercase letters (replace with corresponding capital on input)
125 * 3. N (replace with M on input)
126 * 4. P (replace with B on input)
127 * 5. S (replace with F on input)
129 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
131 const lmno = new LMNO();
133 /* Force a game ID into a canonical form as described above. */
134 function lmno_canonize(id) {
136 id = id.toUpperCase();
138 /* Replace unused letters with nearest phonetic match. */
139 id = id.replace(/N/g, 'M');
140 id = id.replace(/P/g, 'B');
141 id = id.replace(/S/g, 'F');
143 /* Replace unused numbers nearest visual match. */
144 id = id.replace(/0/g, 'O');
145 id = id.replace(/1/g, 'I');
146 id = id.replace(/5/g, 'S');
151 app.post('/new/:game_engine', (request, response) => {
152 const game_engine = request.params.game_engine;
153 const game = lmno.create_game(game_engine);
154 response.send(JSON.stringify(game.id));
157 /* Redirect any requests to a game ID at the top-level.
159 * Specifically, after obtaining the game ID (from the path) we simply
160 * lookup the game engine for the corresponding game and then redirect
161 * to the engine- and game-specific path.
163 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
164 const game_id = request.path.replace(/\//g, "");
165 const canon_id = lmno_canonize(game_id);
167 /* Redirect user to page with the canonical ID in it. */
168 if (game_id !== canon_id) {
169 response.redirect(301, `/${canon_id}/`);
173 const game = lmno.games[game_id];
174 if (game === undefined) {
175 response.sendStatus(404);
178 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
181 /* LMNO middleware to lookup the game. */
182 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
183 const engine = request.params.engine;
184 const game_id = request.params.game_id;
185 const canon_id = lmno_canonize(game_id);
187 /* Redirect user to page with the canonical ID in it, also ensuring
188 * that the game ID is _always_ followed by a slash. */
189 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
190 if (game_id !== canon_id ||
191 ! has_slash.test(request.originalUrl))
193 const old_path = new RegExp(`/${engine}/${game_id}/?`);
194 const new_path = `/${engine}/${canon_id}/`;
195 const new_url = request.originalUrl.replace(old_path, new_path);
196 response.redirect(301, new_url);
200 /* See if there is any game with this ID. */
201 const game = lmno.games[game_id];
202 if (game === undefined) {
203 response.sendStatus(404);
207 /* Stash the game onto the request to be used by the game-specific code. */
212 function auth_admin(request, response, next) {
213 /* If there is no user associated with this session, redirect to the login
214 * page (and set a "next" query parameter so we can come back here).
216 if (! request.session.user) {
217 response.redirect(302, "/login?next=" + request.path);
221 /* If the user is logged in but not authorized to view the page then
222 * we return that error. */
223 if (request.session.user.role !== "admin") {
224 response.status(401).send("Unauthorized");
230 app.get('/logout', (request, response) => {
231 request.session.user = undefined;
232 request.session.destroy();
234 response.send("You are now logged out.");
237 app.get('/login', (request, response) => {
238 if (request.session.user) {
239 response.send("Welcome, " + request.session.user + ".");
243 response.render('login.html');
246 app.post('/login', async (request, response) => {
247 const username = request.body.username;
248 const password = request.body.password;
249 const user = lmno_config.users[username];
251 response.sendStatus(404);
254 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
256 response.sendStatus(404);
259 request.session.user = { username: user.username, role: user.role };
260 response.sendStatus(200);
264 /* API to set uer profile information */
265 app.put('/profile', (request, response) => {
266 const nickname = request.body.nickname;
268 request.session.nickname = nickname;
269 request.session.save();
274 /* An admin page (only available to admin users, of course) */
275 app.get('/admin/', auth_admin, (request, response) => {
279 for (let id in lmno.games) {
280 if (lmno.games[id].players.length)
281 active.push(lmno.games[id]);
283 idle.push(lmno.games[id]);
285 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
289 /* Mount sub apps. only _after_ we have done all the middleware we need. */
290 for (let key in engines) {
291 const engine = engines[key];
292 const router = engine.router;
294 /* Add routes that are common to all games. */
295 router.get('/', (request, response) => {
296 const game = request.game;
298 if (! request.session.nickname) {
299 response.render('choose-nickname.html', {
300 game_name: game.meta.name,
301 options: game.meta.options
304 response.render(`${game.meta.identifier}-game.html`);
308 router.put('/player', (request, response) => {
309 const game = request.game;
311 game.handle_player(request, response);
314 router.get('/events', (request, response) => {
315 const game = request.game;
317 game.handle_events(request, response);
320 /* Further, add some routes conditionally depending on whether the
321 * engine provides specific, necessary methods for the routes. */
323 /* Note: We have to use hasOwnProperty here since the base Game
324 * class has a geeric add_move function, and we don't want that to
325 * have any influence on our decision. Only if the child has
326 * overridden that do we want to create a "/move" route. */
327 if (engine.prototype.hasOwnProperty("add_move")) {
328 router.post('/move', (request, response) => {
329 const game = request.game;
330 const move = request.body.move;
331 const player = game.players_by_session[request.session.id];
333 /* Reject move if there is no player for this session. */
335 response.json({legal: false, message: "No valid player from session"});
339 const result = game.add_move(player, move);
341 /* Take care of any generic post-move work. */
342 game.post_move(player, result);
344 /* Feed move response back to the client. */
345 response.json(result);
347 /* And only if legal, inform all clients. */
351 game.broadcast_move(move);
355 /* And mount the whole router at the path for the game. */
356 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
359 app.listen(4000, function () {
360 console.log('LMNO server listening on localhost:4000');