]> git.cworth.org Git - lmno-server/blob - lmno.js
lmno: Add a new method to create a game with a specific ID value
[lmno-server] / lmno.js
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");
8
9 try {
10   var lmno_config = require("./lmno-config.json");
11 } catch (err) {
12   config_usage();
13   process.exit(1);
14 }
15
16 function config_usage() {
17   console.log(`Error: Refusing to run without configuration.
18
19 Please create a file named lmno-config.json that looks as follows:
20
21 {
22   "session_secret": "<this should be a long string of true-random characters>",
23   "users": {
24     "username": "<username>",
25     "password_hash_bcrypt": "<password_hash_made_by_bcrypt>"
26   }
27 }
28
29 Note: Of course, change all of <these-parts> to actual values desired.
30
31 The "node lmno-passwd.js" command can help generate password hashes.`);
32 }
33
34 const app = express();
35
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.
42  */
43 app.set('trust proxy', true);
44 app.use(cors());
45 app.use(body_parser.urlencoded({ extended: false }));
46 app.use(body_parser.json());
47 app.use(session({
48   secret: lmno_config.session_secret,
49   resave: false,
50   saveUninitialized: false
51 }));
52
53 const njx = nunjucks.configure("templates", {
54   autoescape: true,
55   express: app
56 });
57
58 njx.addFilter('active', function(list) {
59   if (list)
60     return list.filter(e => e.active === true);
61   else
62     return [];
63 });
64
65 njx.addFilter('idle', function(list) {
66   if (list)
67     return list.filter(e => e.active === false);
68   else
69     return [];
70 });
71
72 njx.addFilter('map_prop', function(list, prop) {
73   if (list)
74     return list.map(e => e[prop]);
75   else
76     return [];
77 });
78
79 /* Load each of our game mini-apps.
80  *
81  * Each "engine" we load here must have a property .Game on the
82  * exports object that should be a class that extends the common base
83  * class Game.
84  *
85  * In turn, each engine's Game must have the following properties:
86  *
87  *     .meta:   An object with .name and .identifier properties.
88  *
89  *              Here, .name is a string giving a human-readable name
90  *              for the game, such as "Tic Tac Toe" while .identifier
91  *              is the short, single-word, all-lowercase identifier
92  *              that is used in the path of the URL, such as
93  *              "tictactoe".
94  *
95  *     .router: An express Router object
96  *
97  *              Any game-specific routes should already be on the
98  *              router. Then, LMNO will add common routes including:
99  *
100  *                 /        Serves <identifier>-game.html template
101  *
102  *                 /player  Allows client to set name or team
103  *
104  *                 /events  Serves a stream of events. Game can override
105  *                          the handle_events method, call super() first,
106  *                          and then have code to add custom events.
107  *
108  *                 /moves   Receives move data from clients. This route
109  *                          is only added if the Game class has an
110  *                          add_move method.
111  */
112 const engines = {
113   empires: require("./empires").Game,
114   tictactoe: require("./tictactoe").Game,
115   scribe: require("./scribe").Game,
116   empathy: require("./empathy").Game
117 };
118
119 class LMNO {
120   constructor() {
121     this.games = {};
122   }
123
124   generate_id() {
125     /* Note: The copy from Array(4) to [...Array(4)] is necessary so
126      * that map() will actually work, (which it doesn't on an array
127      * from Array(N) which is in this strange state of having "empty"
128      * items rather than "undefined" as we get after [...Array(4)] */
129     return [...Array(4)].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
130   }
131
132   create_game_with_id(engine_name, id) {
133     if (this.games[id])
134       return null;
135
136     const engine = engines[engine_name];
137
138     const game = new engine(id);
139
140     this.games[id] = game;
141
142     return game;
143   }
144
145   create_game(engine_name) {
146     do {
147       var id = this.generate_id();
148     } while (id in this.games);
149
150     return this.create_game_with_id(engine_name, id);
151   }
152 }
153
154 /* Some letters we don't use in our IDs:
155  *
156  * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
157  * 2. Lowercase letters (replace with corresponding capital on input)
158  * 3. N (replace with M on input)
159  * 4. B (replace with P on input)
160  * 5. F,X (replace with S on input)
161  */
162 LMNO.letters = "CCDDDGGGHHJKLLLLMMMMPPPPQRRRSSSTTTVVWWYYZ";
163
164 const lmno = new LMNO();
165
166 /* Force a game ID into a canonical form as described above. */
167 function lmno_canonize(id) {
168   /* Capitalize */
169   id = id.toUpperCase();
170
171   /* Replace unused letters with nearest phonetic match. */
172   id = id.replace(/N/g, 'M');
173   id = id.replace(/B/g, 'P');
174   id = id.replace(/F/g, 'S');
175   id = id.replace(/X/g, 'S');
176
177   /* Replace unused numbers nearest visual match. */
178   id = id.replace(/0/g, 'O');
179   id = id.replace(/1/g, 'I');
180   id = id.replace(/5/g, 'S');
181
182   return id;
183 }
184
185 app.post('/new/:game_engine', (request, response) =>  {
186   const game_engine = request.params.game_engine;
187   const game = lmno.create_game(game_engine);
188   response.send(JSON.stringify(game.id));
189 });
190
191 /* Redirect any requests to a game ID at the top-level.
192  *
193  * Specifically, after obtaining the game ID (from the path) we simply
194  * lookup the game engine for the corresponding game and then redirect
195  * to the engine- and game-specific path.
196  */
197 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
198   const game_id = request.path.replace(/\//g, "");
199   const canon_id = lmno_canonize(game_id);
200
201   /* Redirect user to page with the canonical ID in it. */
202   if (game_id !== canon_id) {
203     response.redirect(301, `/${canon_id}/`);
204     return;
205   }
206
207   const game = lmno.games[game_id];
208   if (game === undefined) {
209       response.sendStatus(404);
210       return;
211   }
212   response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
213 });
214
215 /* LMNO middleware to lookup the game. */
216 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
217   const engine = request.params.engine;
218   const game_id = request.params.game_id;
219   const canon_id = lmno_canonize(game_id);
220
221   /* Redirect user to page with the canonical ID in it, also ensuring
222    * that the game ID is _always_ followed by a slash. */
223   const has_slash = new RegExp(`^/${engine}/${game_id}/`);
224   if (game_id !== canon_id ||
225       ! has_slash.test(request.originalUrl))
226   {
227     const old_path = new RegExp(`/${engine}/${game_id}/?`);
228     const new_path = `/${engine}/${canon_id}/`;
229     const new_url = request.originalUrl.replace(old_path, new_path);
230     response.redirect(301, new_url);
231     return;
232   }
233
234   /* See if there is any game with this ID. */
235   const game = lmno.games[game_id];
236   if (game === undefined) {
237     response.sendStatus(404);
238     return;
239   }
240
241   /* Stash the game onto the request to be used by the game-specific code. */
242   request.game = game;
243   next();
244 });
245
246 function auth_admin(request, response, next) {
247   /* If there is no user associated with this session, redirect to the login
248    * page (and set a "next" query parameter so we can come back here).
249    */
250   if (! request.session.user) {
251     response.redirect(302, "/login?next=" + request.path);
252     return;
253   }
254
255   /* If the user is logged in but not authorized to view the page then 
256    * we return that error. */
257   if (request.session.user.role !== "admin") {
258     response.status(401).send("Unauthorized");
259     return;
260   }
261   next();
262 }
263
264 app.get('/logout', (request, response) => {
265   request.session.user = undefined;
266   request.session.destroy();
267
268   response.send("You are now logged out.");
269 });
270
271 app.get('/login', (request, response) => {
272   if (request.session.user) {
273     response.send("Welcome, " + request.session.user + ".");
274     return;
275   }
276
277   response.render('login.html');
278 });
279
280 app.post('/login', async (request, response) => {
281   const username = request.body.username;
282   const password = request.body.password;
283   const user = lmno_config.users[username];
284   if (! user) {
285     response.sendStatus(404);
286     return;
287   }
288   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
289   if (! match) {
290     response.sendStatus(404);
291     return;
292   }
293   request.session.user = { username: user.username, role: user.role };
294   response.sendStatus(200);
295   return;
296 });
297
298 /* API to set uer profile information */
299 app.put('/profile', (request, response) => {
300   const nickname = request.body.nickname;
301   if (nickname) {
302     request.session.nickname = nickname;
303     request.session.save();
304   }
305   response.send();
306 });
307
308 /* An admin page (only available to admin users, of course) */
309 app.get('/admin/', auth_admin, (request, response) => {
310   let active = [];
311   let idle = [];
312
313   for (let id in lmno.games) {
314     if (lmno.games[id].players.filter(p => p.active).length > 0)
315       active.push(lmno.games[id]);
316     else
317       idle.push(lmno.games[id]);
318   }
319   response.render('admin.html', { games: { active: active, idle: idle}});
320 });
321
322
323 /* Mount sub apps. only _after_ we have done all the middleware we need. */
324 for (let key in engines) {
325   const engine = engines[key];
326   const router = engine.router;
327
328   /* Add routes that are common to all games. */
329   router.get('/', (request, response) => {
330     const game = request.game;
331
332     if (! request.session.nickname) {
333       response.render('choose-nickname.html', {
334         game_name: game.meta.name,
335         options: game.meta.options
336       });
337     } else {
338       response.render(`${game.meta.identifier}-game.html`);
339     }
340   });
341
342   router.put('/player', (request, response) => {
343     const game = request.game;
344
345     game.handle_player(request, response);
346   });
347
348   router.get('/events', (request, response) => {
349     const game = request.game;
350
351     game.handle_events(request, response);
352   });
353
354   /* Further, add some routes conditionally depending on whether the
355    * engine provides specific, necessary methods for the routes. */
356
357   /* Note: We have to use hasOwnProperty here since the base Game
358    * class has a geeric add_move function, and we don't want that to
359    * have any influence on our decision. Only if the child has
360    * overridden that do we want to create a "/move" route. */
361   if (engine.prototype.hasOwnProperty("add_move")) {
362     router.post('/move', (request, response) => {
363       const game = request.game;
364       const move = request.body.move;
365       const player = game.players_by_session[request.session.id];
366
367       /* Reject move if there is no player for this session. */
368       if (! player) {
369         response.json({legal: false, message: "No valid player from session"});
370         return;
371       }
372
373       const result = game.add_move(player, move);
374
375       /* Take care of any generic post-move work. */
376       game.post_move(player, result);
377
378       /* Feed move response back to the client. */
379       response.json(result);
380
381       /* And only if legal, inform all clients. */
382       if (! result.legal)
383         return;
384
385       game.broadcast_move(move);
386     });
387   }
388
389   /* And mount the whole router at the path for the game. */
390   app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
391 }
392
393 app.listen(4000, function () {
394   console.log('LMNO server listening on localhost:4000');
395 });