]> git.cworth.org Git - empires-server/blob - lmno.js
test: Maintain a list of activated players for automated cleanup
[empires-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(engine_name) {
133     do {
134       var id = this.generate_id();
135     } while (id in this.games);
136
137     const engine = engines[engine_name];
138
139     const game = new engine(id);
140
141     this.games[id] = game;
142
143     return game;
144   }
145 }
146
147 /* Some letters we don't use in our IDs:
148  *
149  * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
150  * 2. Lowercase letters (replace with corresponding capital on input)
151  * 3. N (replace with M on input)
152  * 4. B (replace with P on input)
153  * 5. F,X (replace with S on input)
154  */
155 LMNO.letters = "CCDDDGGGHHJKLLLLMMMMPPPPQRRRSSSTTTVVWWYYZ";
156
157 const lmno = new LMNO();
158
159 /* Force a game ID into a canonical form as described above. */
160 function lmno_canonize(id) {
161   /* Capitalize */
162   id = id.toUpperCase();
163
164   /* Replace unused letters with nearest phonetic match. */
165   id = id.replace(/N/g, 'M');
166   id = id.replace(/B/g, 'P');
167   id = id.replace(/F/g, 'S');
168   id = id.replace(/X/g, 'S');
169
170   /* Replace unused numbers nearest visual match. */
171   id = id.replace(/0/g, 'O');
172   id = id.replace(/1/g, 'I');
173   id = id.replace(/5/g, 'S');
174
175   return id;
176 }
177
178 app.post('/new/:game_engine', (request, response) =>  {
179   const game_engine = request.params.game_engine;
180   const game = lmno.create_game(game_engine);
181   response.send(JSON.stringify(game.id));
182 });
183
184 /* Redirect any requests to a game ID at the top-level.
185  *
186  * Specifically, after obtaining the game ID (from the path) we simply
187  * lookup the game engine for the corresponding game and then redirect
188  * to the engine- and game-specific path.
189  */
190 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
191   const game_id = request.path.replace(/\//g, "");
192   const canon_id = lmno_canonize(game_id);
193
194   /* Redirect user to page with the canonical ID in it. */
195   if (game_id !== canon_id) {
196     response.redirect(301, `/${canon_id}/`);
197     return;
198   }
199
200   const game = lmno.games[game_id];
201   if (game === undefined) {
202       response.sendStatus(404);
203       return;
204   }
205   response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
206 });
207
208 /* LMNO middleware to lookup the game. */
209 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
210   const engine = request.params.engine;
211   const game_id = request.params.game_id;
212   const canon_id = lmno_canonize(game_id);
213
214   /* Redirect user to page with the canonical ID in it, also ensuring
215    * that the game ID is _always_ followed by a slash. */
216   const has_slash = new RegExp(`^/${engine}/${game_id}/`);
217   if (game_id !== canon_id ||
218       ! has_slash.test(request.originalUrl))
219   {
220     const old_path = new RegExp(`/${engine}/${game_id}/?`);
221     const new_path = `/${engine}/${canon_id}/`;
222     const new_url = request.originalUrl.replace(old_path, new_path);
223     response.redirect(301, new_url);
224     return;
225   }
226
227   /* See if there is any game with this ID. */
228   const game = lmno.games[game_id];
229   if (game === undefined) {
230     response.sendStatus(404);
231     return;
232   }
233
234   /* Stash the game onto the request to be used by the game-specific code. */
235   request.game = game;
236   next();
237 });
238
239 function auth_admin(request, response, next) {
240   /* If there is no user associated with this session, redirect to the login
241    * page (and set a "next" query parameter so we can come back here).
242    */
243   if (! request.session.user) {
244     response.redirect(302, "/login?next=" + request.path);
245     return;
246   }
247
248   /* If the user is logged in but not authorized to view the page then 
249    * we return that error. */
250   if (request.session.user.role !== "admin") {
251     response.status(401).send("Unauthorized");
252     return;
253   }
254   next();
255 }
256
257 app.get('/logout', (request, response) => {
258   request.session.user = undefined;
259   request.session.destroy();
260
261   response.send("You are now logged out.");
262 });
263
264 app.get('/login', (request, response) => {
265   if (request.session.user) {
266     response.send("Welcome, " + request.session.user + ".");
267     return;
268   }
269
270   response.render('login.html');
271 });
272
273 app.post('/login', async (request, response) => {
274   const username = request.body.username;
275   const password = request.body.password;
276   const user = lmno_config.users[username];
277   if (! user) {
278     response.sendStatus(404);
279     return;
280   }
281   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
282   if (! match) {
283     response.sendStatus(404);
284     return;
285   }
286   request.session.user = { username: user.username, role: user.role };
287   response.sendStatus(200);
288   return;
289 });
290
291 /* API to set uer profile information */
292 app.put('/profile', (request, response) => {
293   const nickname = request.body.nickname;
294   if (nickname) {
295     request.session.nickname = nickname;
296     request.session.save();
297   }
298   response.send();
299 });
300
301 /* An admin page (only available to admin users, of course) */
302 app.get('/admin/', auth_admin, (request, response) => {
303   let active = [];
304   let idle = [];
305
306   for (let id in lmno.games) {
307     if (lmno.games[id].players.filter(p => p.active).length > 0)
308       active.push(lmno.games[id]);
309     else
310       idle.push(lmno.games[id]);
311   }
312   response.render('admin.html', { games: { active: active, idle: idle}});
313 });
314
315
316 /* Mount sub apps. only _after_ we have done all the middleware we need. */
317 for (let key in engines) {
318   const engine = engines[key];
319   const router = engine.router;
320
321   /* Add routes that are common to all games. */
322   router.get('/', (request, response) => {
323     const game = request.game;
324
325     if (! request.session.nickname) {
326       response.render('choose-nickname.html', {
327         game_name: game.meta.name,
328         options: game.meta.options
329       });
330     } else {
331       response.render(`${game.meta.identifier}-game.html`);
332     }
333   });
334
335   router.put('/player', (request, response) => {
336     const game = request.game;
337
338     game.handle_player(request, response);
339   });
340
341   router.get('/events', (request, response) => {
342     const game = request.game;
343
344     game.handle_events(request, response);
345   });
346
347   /* Further, add some routes conditionally depending on whether the
348    * engine provides specific, necessary methods for the routes. */
349
350   /* Note: We have to use hasOwnProperty here since the base Game
351    * class has a geeric add_move function, and we don't want that to
352    * have any influence on our decision. Only if the child has
353    * overridden that do we want to create a "/move" route. */
354   if (engine.prototype.hasOwnProperty("add_move")) {
355     router.post('/move', (request, response) => {
356       const game = request.game;
357       const move = request.body.move;
358       const player = game.players_by_session[request.session.id];
359
360       /* Reject move if there is no player for this session. */
361       if (! player) {
362         response.json({legal: false, message: "No valid player from session"});
363         return;
364       }
365
366       const result = game.add_move(player, move);
367
368       /* Take care of any generic post-move work. */
369       game.post_move(player, result);
370
371       /* Feed move response back to the client. */
372       response.json(result);
373
374       /* And only if legal, inform all clients. */
375       if (! result.legal)
376         return;
377
378       game.broadcast_move(move);
379     });
380   }
381
382   /* And mount the whole router at the path for the game. */
383   app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router);
384 }
385
386 app.listen(4000, function () {
387   console.log('LMNO server listening on localhost:4000');
388 });