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
93 return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
96 create_game(engine_name) {
98 var id = this.generate_id();
99 } while (id in this.games);
101 const engine = engines[engine_name];
103 const game = new engine(id);
105 this.games[id] = game;
111 /* Some letters we don't use in our IDs:
113 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
114 * 2. Lowercase letters (replace with corresponding capital on input)
115 * 3. N (replace with M on input)
116 * 4. P (replace with B on input)
117 * 5. S (replace with F on input)
119 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
121 const lmno = new LMNO();
123 /* Force a game ID into a canonical form as described above. */
124 function lmno_canonize(id) {
126 id = id.toUpperCase();
128 /* Replace unused letters with nearest phonetic match. */
129 id = id.replace(/N/g, 'M');
130 id = id.replace(/P/g, 'B');
131 id = id.replace(/S/g, 'F');
133 /* Replace unused numbers nearest visual match. */
134 id = id.replace(/0/g, 'O');
135 id = id.replace(/1/g, 'I');
136 id = id.replace(/5/g, 'S');
141 app.post('/new/:game_engine', (request, response) => {
142 const game_engine = request.params.game_engine;
143 const game = lmno.create_game(game_engine);
144 response.send(JSON.stringify(game.id));
147 /* Redirect any requests to a game ID at the top-level.
149 * Specifically, after obtaining the game ID (from the path) we simply
150 * lookup the game engine for the corresponding game and then redirect
151 * to the engine- and game-specific path.
153 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
154 const game_id = request.path.replace(/\//g, "");
155 const canon_id = lmno_canonize(game_id);
157 /* Redirect user to page with the canonical ID in it. */
158 if (game_id !== canon_id) {
159 response.redirect(301, `/${canon_id}/`);
163 const game = lmno.games[game_id];
164 if (game === undefined) {
165 response.sendStatus(404);
168 response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
171 /* LMNO middleware to lookup the game. */
172 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
173 const engine = request.params.engine;
174 const game_id = request.params.game_id;
175 const canon_id = lmno_canonize(game_id);
177 /* Redirect user to page with the canonical ID in it, also ensuring
178 * that the game ID is _always_ followed by a slash. */
179 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
180 if (game_id !== canon_id ||
181 ! has_slash.test(request.originalUrl))
183 const old_path = new RegExp(`/${engine}/${game_id}/?`);
184 const new_path = `/${engine}/${canon_id}/`;
185 const new_url = request.originalUrl.replace(old_path, new_path);
186 response.redirect(301, new_url);
190 /* See if there is any game with this ID. */
191 const game = lmno.games[game_id];
192 if (game === undefined) {
193 response.sendStatus(404);
197 /* Stash the game onto the request to be used by the game-specific code. */
202 function auth_admin(request, response, next) {
203 /* If there is no user associated with this session, redirect to the login
204 * page (and set a "next" query parameter so we can come back here).
206 if (! request.session.user) {
207 response.redirect(302, "/login?next=" + request.path);
211 /* If the user is logged in but not authorized to view the page then
212 * we return that error. */
213 if (request.session.user.role !== "admin") {
214 response.status(401).send("Unauthorized");
220 app.get('/logout', (request, response) => {
221 request.session.user = undefined;
222 request.session.destroy();
224 response.send("You are now logged out.");
227 app.get('/login', (request, response) => {
228 if (request.session.user) {
229 response.send("Welcome, " + request.session.user + ".");
233 response.render('login.html');
236 app.post('/login', async (request, response) => {
237 const username = request.body.username;
238 const password = request.body.password;
239 const user = lmno_config.users[username];
241 response.sendStatus(404);
244 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
246 response.sendStatus(404);
249 request.session.user = { username: user.username, role: user.role };
250 response.sendStatus(200);
254 /* API to set uer profile information */
255 app.put('/profile', (request, response) => {
256 const nickname = request.body.nickname;
258 request.session.nickname = nickname;
259 request.session.save();
264 /* An admin page (only available to admin users, of course) */
265 app.get('/admin/', auth_admin, (request, response) => {
269 for (let id in lmno.games) {
270 if (lmno.games[id].clients.length)
271 active.push(lmno.games[id]);
273 idle.push(lmno.games[id]);
275 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
279 /* Mount sub apps. only _after_ we have done all the middleware we need. */
280 for (let key in engines) {
281 const engine = engines[key];
282 const router = engine.router;
284 /* Add routes that are common to all games. */
285 router.get('/', (request, response) => {
286 const game = request.game;
288 if (! request.session.nickname)
289 response.render('choose-nickname.html', { game_name: game.meta.name });
291 response.render(`${game.meta.identifier}-game.html`);
294 router.put('/player', (request, response) => {
295 const game = request.game;
297 game.handle_player(request, response);
300 router.get('/events', (request, response) => {
301 const game = request.game;
303 game.handle_events(request, response);
306 /* Further, add some routes conditionally depending on whether the
307 * engine provides specific, necessary methods for the routes. */
308 if (engine.prototype.add_move) {
309 router.post('/move', (request, response) => {
310 const game = request.game;
311 const move = request.body.move;
312 const player = game.players[request.session.id];
314 /* Reject move if there is no player for this session. */
316 response.json({legal: false, message: "No valid player from session"});
320 const result = game.add_move(player, move);
322 /* Feed move response back to the client. */
323 response.json(result);
325 /* And only if legal, inform all clients. */
329 game.broadcast_move(move);
333 /* And mount the whole router at the path for the game. */
334 app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
337 app.listen(4000, function () {
338 console.log('LMNO server listening on localhost:4000');