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