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