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 * /events Serves a stream of events. Game can override
73 * the handle_events method, call super() first,
74 * and then have code to add custom events.
76 * /moves Receives move data from clients. This route
77 * is only added if the Game class has an
81 empires: require("./empires").Game,
82 tictactoe: require("./tictactoe").Game
91 return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
94 create_game(engine_name) {
96 var id = this.generate_id();
97 } while (id in this.games);
99 const engine = engines[engine_name];
101 const game = new engine(id);
103 this.games[id] = game;
109 /* Some letters we don't use in our IDs:
111 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
112 * 2. Lowercase letters (replace with corresponding capital on input)
113 * 3. N (replace with M on input)
114 * 4. P (replace with B on input)
115 * 5. S (replace with F on input)
117 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
119 const lmno = new LMNO();
121 /* Force a game ID into a canonical form as described above. */
122 function lmno_canonize(id) {
124 id = id.toUpperCase();
126 /* Replace unused letters with nearest phonetic match. */
127 id = id.replace(/N/g, 'M');
128 id = id.replace(/P/g, 'B');
129 id = id.replace(/S/g, 'F');
131 /* Replace unused numbers nearest visual match. */
132 id = id.replace(/0/g, 'O');
133 id = id.replace(/1/g, 'I');
134 id = id.replace(/5/g, 'S');
139 app.post('/new/:game_engine', (request, response) => {
140 const game_engine = request.params.game_engine;
141 const game = lmno.create_game(game_engine);
142 response.send(JSON.stringify(game.id));
145 /* Redirect any requests to a game ID at the top-level.
147 * Specifically, after obtaining the game ID (from the path) we simply
148 * lookup the game engine for the corresponding game and then redirect
149 * to the engine- and game-specific path.
151 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
152 const game_id = request.path.replace(/\//g, "");
153 const canon_id = lmno_canonize(game_id);
155 /* Redirect user to page with the canonical ID in it. */
156 if (game_id !== canon_id) {
157 response.redirect(301, `/${canon_id}/`);
161 const game = lmno.games[game_id];
162 if (game === undefined) {
163 response.sendStatus(404);
166 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
169 /* LMNO middleware to lookup the game. */
170 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
171 const engine = request.params.engine;
172 const game_id = request.params.game_id;
173 const canon_id = lmno_canonize(game_id);
175 /* Redirect user to page with the canonical ID in it, also ensuring
176 * that the game ID is _always_ followed by a slash. */
177 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
178 if (game_id !== canon_id ||
179 ! has_slash.test(request.originalUrl))
181 const old_path = new RegExp(`/${engine}/${game_id}/?`);
182 const new_path = `/${engine}/${canon_id}/`;
183 const new_url = request.originalUrl.replace(old_path, new_path);
184 response.redirect(301, new_url);
188 /* See if there is any game with this ID. */
189 const game = lmno.games[game_id];
190 if (game === undefined) {
191 response.sendStatus(404);
195 /* Stash the game onto the request to be used by the game-specific code. */
200 function auth_admin(request, response, next) {
201 /* If there is no user associated with this session, redirect to the login
202 * page (and set a "next" query parameter so we can come back here).
204 if (! request.session.user) {
205 response.redirect(302, "/login?next=" + request.path);
209 /* If the user is logged in but not authorized to view the page then
210 * we return that error. */
211 if (request.session.user.role !== "admin") {
212 response.status(401).send("Unauthorized");
218 app.get('/logout', (request, response) => {
219 request.session.user = undefined;
220 request.session.destroy();
222 response.send("You are now logged out.");
225 app.get('/login', (request, response) => {
226 if (request.session.user) {
227 response.send("Welcome, " + request.session.user + ".");
231 response.render('login.html');
234 app.post('/login', async (request, response) => {
235 const username = request.body.username;
236 const password = request.body.password;
237 const user = lmno_config.users[username];
239 response.sendStatus(404);
242 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
244 response.sendStatus(404);
247 request.session.user = { username: user.username, role: user.role };
248 response.sendStatus(200);
252 /* API to set uer profile information */
253 app.put('/profile', (request, response) => {
254 const nickname = request.body.nickname;
256 request.session.nickname = nickname;
257 request.session.save();
262 /* An admin page (only available to admin users, of course) */
263 app.get('/admin/', auth_admin, (request, response) => {
267 for (let id in lmno.games) {
268 if (lmno.games[id].clients.length)
269 active.push(lmno.games[id]);
271 idle.push(lmno.games[id]);
273 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
277 /* Mount sub apps. only _after_ we have done all the middleware we need. */
278 for (let key in engines) {
279 const engine = engines[key];
280 const router = engine.router;
282 /* Add routes that are common to all games. */
283 router.get('/', (request, response) => {
284 const game = request.game;
286 if (! request.session.nickname)
287 response.render('choose-nickname.html', { game_name: game.meta.name });
289 response.render(`${game.meta.identifier}-game.html`);
292 router.get('/events', (request, response) => {
293 const game = request.game;
295 game.handle_events(request, response);
298 /* Further, add some routes conditionally depending on whether the
299 * engine provides specific, necessary methods for the routes. */
300 if (engine.prototype.add_move) {
301 router.post('/move', (request, response) => {
302 const game = request.game;
303 const move = request.body.move;
305 const result = game.add_move(move);
307 /* Feed move response back to the client. */
308 response.json(result);
310 /* And only if legal, inform all clients. */
314 game.broadcast_move(move);
318 /* And mount the whole router at the path for the game. */
319 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
322 app.listen(4000, function () {
323 console.log('LMNO server listening on localhost:4000');