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