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