X-Git-Url: https://git.cworth.org/git?p=empires-server;a=blobdiff_plain;f=lmno.js;h=54baea91f8d5688a74071fa45d19a12cd13ae091;hp=dc23fc2556651626905bae6f10a47cf5fe227c3f;hb=HEAD;hpb=67ddcfdfc632fc081ae267d6482082ddfe1635aa diff --git a/lmno.js b/lmno.js index dc23fc2..54baea9 100644 --- a/lmno.js +++ b/lmno.js @@ -1,33 +1,154 @@ const express = require("express"); const cors = require("cors"); const body_parser = require("body-parser"); +const session = require("express-session"); +const bcrypt = require("bcrypt"); +const path = require("path"); +const nunjucks = require("nunjucks"); + +try { + var lmno_config = require("./lmno-config.json"); +} catch (err) { + config_usage(); + process.exit(1); +} + +function config_usage() { + console.log(`Error: Refusing to run without configuration. + +Please create a file named lmno-config.json that looks as follows: + +{ + "session_secret": "", + "users": { + "username": "", + "password_hash_bcrypt": "" + } +} + +Note: Of course, change all of to actual values desired. + +The "node lmno-passwd.js" command can help generate password hashes.`); +} const app = express(); + +/* This 'trust proxy' option, (and, really? a space in an option + * name?!) means that express will grab hostname and IP values from + * the X-Forwarded-* header fields. We need that so that our games + * will display a proper hostname of https://lmno.games/WXYZ instead + * of http://localhost/QFBL which will obviously not be a helpful + * thing to share around. + */ +app.set('trust proxy', true); app.use(cors()); +app.use(body_parser.urlencoded({ extended: false })); +app.use(body_parser.json()); +app.use(session({ + secret: lmno_config.session_secret, + resave: false, + saveUninitialized: false +})); + +const njx = nunjucks.configure("templates", { + autoescape: true, + express: app +}); + +njx.addFilter('active', function(list) { + if (list) + return list.filter(e => e.active === true); + else + return []; +}); + +njx.addFilter('idle', function(list) { + if (list) + return list.filter(e => e.active === false); + else + return []; +}); + +njx.addFilter('map_prop', function(list, prop) { + if (list) + return list.map(e => e[prop]); + else + return []; +}); + +/* Load each of our game mini-apps. + * + * Each "engine" we load here must have a property .Game on the + * exports object that should be a class that extends the common base + * class Game. + * + * In turn, each engine's Game must have the following properties: + * + * .meta: An object with .name and .identifier properties. + * + * Here, .name is a string giving a human-readable name + * for the game, such as "Tic Tac Toe" while .identifier + * is the short, single-word, all-lowercase identifier + * that is used in the path of the URL, such as + * "tictactoe". + * + * .router: An express Router object + * + * Any game-specific routes should already be on the + * router. Then, LMNO will add common routes including: + * + * / Serves -game.html template + * + * /player Allows client to set name or team + * + * /events Serves a stream of events. Game can override + * the handle_events method, call super() first, + * and then have code to add custom events. + * + * /moves Receives move data from clients. This route + * is only added if the Game class has an + * add_move method. + */ +const engines = { + empires: require("./empires").Game, + tictactoe: require("./tictactoe").Game, + scribe: require("./scribe").Game, + empathy: require("./empathy").Game +}; class LMNO { constructor() { - this.ids = {}; + this.games = {}; } generate_id() { - return [null,null,null,null].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join(''); + /* Note: The copy from Array(4) to [...Array(4)] is necessary so + * that map() will actually work, (which it doesn't on an array + * from Array(N) which is in this strange state of having "empty" + * items rather than "undefined" as we get after [...Array(4)] */ + return [...Array(4)].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join(''); } - create_game(engine) { - do { - var id = this.generate_id(); - } while (id in this.ids); + create_game_with_id(engine_name, id) { + if (this.games[id]) + return null; + + const engine = engines[engine_name]; - const game = { - id: id, - engine: engine, - }; + const game = new engine(id); - this.ids[id] = game; + this.games[id] = game; return game; } + + create_game(engine_name) { + do { + var id = this.generate_id(); + } while (id in this.games); + + return this.create_game_with_id(engine_name, id); + } } /* Some letters we don't use in our IDs: @@ -35,19 +156,247 @@ class LMNO { * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word * 2. Lowercase letters (replace with corresponding capital on input) * 3. N (replace with M on input) - * 4. P (replace with B on input) - * 5. S (replace with F on input) + * 4. B (replace with P on input) + * 5. F,X (replace with S on input) */ -LMNO.letters = "BCDFGHJKLMQRTVWXYZ"; +LMNO.letters = "CCDDDGGGHHJKLLLLMMMMPPPPQRRRSSSTTTVVWWYYZ"; const lmno = new LMNO(); +/* Pre-allocate an empires game with ID QRST. + * This is for convenience in the development of the flempires + * client which would like to have stable API endpoints across + * server restarts. + */ +lmno.create_game_with_id("empires", "QRST"); + +/* Force a game ID into a canonical form as described above. */ +function lmno_canonize(id) { + /* Capitalize */ + id = id.toUpperCase(); + + /* Replace unused letters with nearest phonetic match. */ + id = id.replace(/N/g, 'M'); + id = id.replace(/B/g, 'P'); + id = id.replace(/F/g, 'S'); + id = id.replace(/X/g, 'S'); + + /* Replace unused numbers nearest visual match. */ + id = id.replace(/0/g, 'O'); + id = id.replace(/1/g, 'I'); + id = id.replace(/5/g, 'S'); + + return id; +} + app.post('/new/:game_engine', (request, response) => { const game_engine = request.params.game_engine; const game = lmno.create_game(game_engine); response.send(JSON.stringify(game.id)); }); +/* Redirect any requests to a game ID at the top-level. + * + * Specifically, after obtaining the game ID (from the path) we simply + * lookup the game engine for the corresponding game and then redirect + * to the engine- and game-specific path. + */ +app.get('/[a-zA-Z0-9]{4}', (request, response) => { + const game_id = request.path.replace(/\//g, ""); + const canon_id = lmno_canonize(game_id); + + /* Redirect user to page with the canonical ID in it. */ + if (game_id !== canon_id) { + response.redirect(301, `/${canon_id}/`); + return; + } + + const game = lmno.games[game_id]; + if (game === undefined) { + response.sendStatus(404); + return; + } + response.redirect(301, `/${game.meta.identifier}/${game.id}/`); +}); + +/* LMNO middleware to lookup the game. */ +app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => { + const engine = request.params.engine; + const game_id = request.params.game_id; + const canon_id = lmno_canonize(game_id); + + /* Redirect user to page with the canonical ID in it, also ensuring + * that the game ID is _always_ followed by a slash. */ + const has_slash = new RegExp(`^/${engine}/${game_id}/`); + if (game_id !== canon_id || + ! has_slash.test(request.originalUrl)) + { + const old_path = new RegExp(`/${engine}/${game_id}/?`); + const new_path = `/${engine}/${canon_id}/`; + const new_url = request.originalUrl.replace(old_path, new_path); + response.redirect(301, new_url); + return; + } + + /* See if there is any game with this ID. */ + const game = lmno.games[game_id]; + if (game === undefined) { + response.sendStatus(404); + return; + } + + /* Stash the game onto the request to be used by the game-specific code. */ + request.game = game; + next(); +}); + +function auth_admin(request, response, next) { + /* If there is no user associated with this session, redirect to the login + * page (and set a "next" query parameter so we can come back here). + */ + if (! request.session.user) { + response.redirect(302, "/login?next=" + request.path); + return; + } + + /* If the user is logged in but not authorized to view the page then + * we return that error. */ + if (request.session.user.role !== "admin") { + response.status(401).send("Unauthorized"); + return; + } + next(); +} + +app.get('/logout', (request, response) => { + request.session.user = undefined; + request.session.destroy(); + + response.send("You are now logged out."); +}); + +app.get('/login', (request, response) => { + if (request.session.user) { + response.send("Welcome, " + request.session.user + "."); + return; + } + + response.render('login.html'); +}); + +app.post('/login', async (request, response) => { + const username = request.body.username; + const password = request.body.password; + const user = lmno_config.users[username]; + if (! user) { + response.sendStatus(404); + return; + } + const match = await bcrypt.compare(password, user.password_hash_bcrypt); + if (! match) { + response.sendStatus(404); + return; + } + request.session.user = { username: user.username, role: user.role }; + response.sendStatus(200); + return; +}); + +/* API to set user profile information */ +app.put('/profile', (request, response) => { + const nickname = request.body.nickname; + if (nickname) { + request.session.nickname = nickname; + request.session.save(); + } + response.send(); +}); + +/* An admin page (only available to admin users, of course) */ +app.get('/admin/', auth_admin, (request, response) => { + let active = []; + let idle = []; + + for (let id in lmno.games) { + if (lmno.games[id].players.filter(p => p.active).length > 0) + active.push(lmno.games[id]); + else + idle.push(lmno.games[id]); + } + response.render('admin.html', { games: { active: active, idle: idle}}); +}); + + +/* Mount sub apps. only _after_ we have done all the middleware we need. */ +for (let key in engines) { + const engine = engines[key]; + const router = engine.router; + + /* Add routes that are common to all games. */ + router.get('/', (request, response) => { + const game = request.game; + + if (! request.session.nickname) { + response.render('choose-nickname.html', { + game_name: game.meta.name, + options: game.meta.options + }); + } else { + response.render(`${game.meta.identifier}-game.html`); + } + }); + + router.put('/player', (request, response) => { + const game = request.game; + + game.handle_player(request, response); + }); + + router.get('/events', (request, response) => { + const game = request.game; + + game.handle_events(request, response); + }); + + /* Further, add some routes conditionally depending on whether the + * engine provides specific, necessary methods for the routes. */ + + /* Note: We have to use hasOwnProperty here since the base Game + * class has a geeric add_move function, and we don't want that to + * have any influence on our decision. Only if the child has + * overridden that do we want to create a "/move" route. */ + if (engine.prototype.hasOwnProperty("add_move")) { + router.post('/move', (request, response) => { + const game = request.game; + const move = request.body.move; + const player = game.players_by_session[request.session.id]; + + /* Reject move if there is no player for this session. */ + if (! player) { + response.json({legal: false, message: "No valid player from session"}); + return; + } + + const result = game.add_move(player, move); + + /* Take care of any generic post-move work. */ + game.post_move(player, result); + + /* Feed move response back to the client. */ + response.json(result); + + /* And only if legal, inform all clients. */ + if (! result.legal) + return; + + game.broadcast_move(move); + }); + } + + /* And mount the whole router at the path for the game. */ + app.use(`/${engine.meta.identifier}/[a-zA-Z0-9]{4}/`, router); +} + app.listen(4000, function () { console.log('LMNO server listening on localhost:4000'); });