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 app.use(body_parser.urlencoded({ extended: false }));
37 app.use(body_parser.json());
39 secret: lmno_config.session_secret,
41 saveUninitialized: false
44 nunjucks.configure("templates", {
49 /* Load each of our game mini-apps.
51 * Each "engine" we load here must have a property .Game on the
52 * exports object that should be a class that extends the common base
55 * In turn, each engine's Game must have the following properties:
57 * .meta: An object with .name and .identifier properties.
59 * Here, .name is a string giving a human-readable name
60 * for the game, such as "Tic Tac Toe" while .identifier
61 * is the short, single-word, all-lowercase identifier
62 * that is used in the path of the URL, such as
65 * .router: An express Router object
67 * Any game-specific routes should already be on the
68 * router. Then, LMNO will add common routes including:
70 * / Serves <identifier>-game.html template
72 * /player Allows client to set name or team
74 * /events Serves a stream of events. Game can override
75 * the handle_events method, call super() first,
76 * and then have code to add custom events.
78 * /moves Receives move data from clients. This route
79 * is only added if the Game class has an
83 empires: require("./empires").Game,
84 tictactoe: require("./tictactoe").Game,
85 scribe: require("./scribe").Game
94 return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
97 create_game(engine_name) {
99 var id = this.generate_id();
100 } while (id in this.games);
102 const engine = engines[engine_name];
104 const game = new engine(id);
106 this.games[id] = game;
112 /* Some letters we don't use in our IDs:
114 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
115 * 2. Lowercase letters (replace with corresponding capital on input)
116 * 3. N (replace with M on input)
117 * 4. P (replace with B on input)
118 * 5. S (replace with F on input)
120 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
122 const lmno = new LMNO();
124 /* Force a game ID into a canonical form as described above. */
125 function lmno_canonize(id) {
127 id = id.toUpperCase();
129 /* Replace unused letters with nearest phonetic match. */
130 id = id.replace(/N/g, 'M');
131 id = id.replace(/P/g, 'B');
132 id = id.replace(/S/g, 'F');
134 /* Replace unused numbers nearest visual match. */
135 id = id.replace(/0/g, 'O');
136 id = id.replace(/1/g, 'I');
137 id = id.replace(/5/g, 'S');
142 app.post('/new/:game_engine', (request, response) => {
143 const game_engine = request.params.game_engine;
144 const game = lmno.create_game(game_engine);
145 response.send(JSON.stringify(game.id));
148 /* Redirect any requests to a game ID at the top-level.
150 * Specifically, after obtaining the game ID (from the path) we simply
151 * lookup the game engine for the corresponding game and then redirect
152 * to the engine- and game-specific path.
154 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
155 const game_id = request.path.replace(/\//g, "");
156 const canon_id = lmno_canonize(game_id);
158 /* Redirect user to page with the canonical ID in it. */
159 if (game_id !== canon_id) {
160 response.redirect(301, `/${canon_id}/`);
164 const game = lmno.games[game_id];
165 if (game === undefined) {
166 response.sendStatus(404);
169 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
172 /* LMNO middleware to lookup the game. */
173 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
174 const engine = request.params.engine;
175 const game_id = request.params.game_id;
176 const canon_id = lmno_canonize(game_id);
178 /* Redirect user to page with the canonical ID in it, also ensuring
179 * that the game ID is _always_ followed by a slash. */
180 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
181 if (game_id !== canon_id ||
182 ! has_slash.test(request.originalUrl))
184 const old_path = new RegExp(`/${engine}/${game_id}/?`);
185 const new_path = `/${engine}/${canon_id}/`;
186 const new_url = request.originalUrl.replace(old_path, new_path);
187 response.redirect(301, new_url);
191 /* See if there is any game with this ID. */
192 const game = lmno.games[game_id];
193 if (game === undefined) {
194 response.sendStatus(404);
198 /* Stash the game onto the request to be used by the game-specific code. */
203 function auth_admin(request, response, next) {
204 /* If there is no user associated with this session, redirect to the login
205 * page (and set a "next" query parameter so we can come back here).
207 if (! request.session.user) {
208 response.redirect(302, "/login?next=" + request.path);
212 /* If the user is logged in but not authorized to view the page then
213 * we return that error. */
214 if (request.session.user.role !== "admin") {
215 response.status(401).send("Unauthorized");
221 app.get('/logout', (request, response) => {
222 request.session.user = undefined;
223 request.session.destroy();
225 response.send("You are now logged out.");
228 app.get('/login', (request, response) => {
229 if (request.session.user) {
230 response.send("Welcome, " + request.session.user + ".");
234 response.render('login.html');
237 app.post('/login', async (request, response) => {
238 const username = request.body.username;
239 const password = request.body.password;
240 const user = lmno_config.users[username];
242 response.sendStatus(404);
245 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
247 response.sendStatus(404);
250 request.session.user = { username: user.username, role: user.role };
251 response.sendStatus(200);
255 /* API to set uer profile information */
256 app.put('/profile', (request, response) => {
257 const nickname = request.body.nickname;
259 request.session.nickname = nickname;
260 request.session.save();
265 /* An admin page (only available to admin users, of course) */
266 app.get('/admin/', auth_admin, (request, response) => {
270 for (let id in lmno.games) {
271 if (lmno.games[id].players.length)
272 active.push(lmno.games[id]);
274 idle.push(lmno.games[id]);
276 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
280 /* Mount sub apps. only _after_ we have done all the middleware we need. */
281 for (let key in engines) {
282 const engine = engines[key];
283 const router = engine.router;
285 /* Add routes that are common to all games. */
286 router.get('/', (request, response) => {
287 const game = request.game;
289 if (! request.session.nickname) {
290 response.render('choose-nickname.html', {
291 game_name: game.meta.name,
292 options: game.meta.options
295 response.render(`${game.meta.identifier}-game.html`);
299 router.put('/player', (request, response) => {
300 const game = request.game;
302 game.handle_player(request, response);
305 router.get('/events', (request, response) => {
306 const game = request.game;
308 game.handle_events(request, response);
311 /* Further, add some routes conditionally depending on whether the
312 * engine provides specific, necessary methods for the routes. */
314 /* Note: We have to use hasOwnProperty here since the base Game
315 * class has a geeric add_move function, and we don't want that to
316 * have any influence on our decision. Only if the child has
317 * overridden that do we want to create a "/move" route. */
318 if (engine.prototype.hasOwnProperty("add_move")) {
319 router.post('/move', (request, response) => {
320 const game = request.game;
321 const move = request.body.move;
322 const player = game.players_by_session[request.session.id];
324 /* Reject move if there is no player for this session. */
326 response.json({legal: false, message: "No valid player from session"});
330 const result = game.add_move(player, move);
332 /* Take care of any generic post-move work. */
333 game.post_move(player, result);
335 /* Feed move response back to the client. */
336 response.json(result);
338 /* And only if legal, inform all clients. */
342 game.broadcast_move(move);
346 /* And mount the whole router at the path for the game. */
347 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
350 app.listen(4000, function () {
351 console.log('LMNO server listening on localhost:4000');