Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·532 lines (474 loc) · 19 KB
/
Copy pathserver.js
File metadata and controls
executable file
·532 lines (474 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// Main entry point for the server. Init systems, sync client js and data, listen for connections
const USERNAME_RESTRICTIONS = {min:3, max:50};
const PASSWORD_RESTRICTIONS = {min:8, max:50};
let httpServer,
fs = require('fs'),
express = require('express'),
app = express(),
server,
session = require('express-session'),
pug = require('pug'),
bodyParser = require('body-parser'),
bcrypt = require('bcrypt'),
Promise = require('bluebird'),
db = require('sqlite'),
sessionFileStore = require('session-file-store')(session),
validator = require('validator'),
ExpressBrute = require('express-brute'),
BruteMemcachedStore = require('express-brute-memcached'),
SessionMemcachedStore = require('connect-memcached')(session);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
let sessionOptions = {
cookie: {}, resave: false, saveUninitialized: false,
secret: fs.readFileSync('../session.secret').toString(), autoSave: true
};
let sessionObject;
let bruteStore = {};
// Don't let the server start unless an environment is specifically chosen
if(process.argv.length !== 3 || (process.argv[2] !== "debug" && process.argv[2] !== "production")){
console.error("Usage: nodejs server.js (debug|production)");
process.exit();
}
// When running in a dev environment, it is just easier to only use HTTP rather than HTTPS
if(process.argv[2] === "debug") {
console.info("Running as debug");
sessionOptions.cookie.secure = false;
sessionOptions.store = new sessionFileStore();
httpServer = require('http');
sessionObject = session(sessionOptions);
app.use(sessionObject);
server = httpServer.createServer(app);
bruteStore = new ExpressBrute.MemoryStore();
}
else {
console.info("Running as production");
// Secure cookies can only be used with HTTPS
sessionOptions.cookie.secure = true;
sessionOptions.store = new SessionMemcachedStore({hosts:'127.0.0.1:11211'});
// Don't allow non-HTTPS connections
let unsecureHttpServer = require('http');
unsecureHttpServer.createServer(function(req, res) {
res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});
res.end();
}).listen(8080);
httpServer = require('https');
let options = {
key: fs.readFileSync('/etc/letsencrypt/live/granitegames.io/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/granitegames.io/fullchain.pem')
};
// To handle when the certificate rotates. Conns already established will use the old cert, and new conns will
// use the new cert data
// https://github.com/nodejs/node/issues/4464
fs.watch('/etc/letsencrypt/live/granitegames.io/', () => {
options.server._sharedCreds.context.setKey(fs.readFileSync('/etc/letsencrypt/live/granitegames.io/privkey.pem'));
options.server._sharedCreds.context.setCert(fs.readFileSync('/etc/letsencrypt/live/granitegames.io/fullchain.pem'));
});
sessionObject = session(sessionOptions);
app.use(sessionObject);
server = httpServer.createServer(options, app);
bruteStore = new BruteMemcachedStore('127.0.0.1:11211');
}
var bruteforce = new ExpressBrute(bruteStore);
app.set('view engine', 'pug');
const { Server } = require("socket.io");
const io = new Server(server);
var communicationsjs = require('./engine/communications.js'),
citiesjs = require('./engine/cities.js'),
powerPlantReaderjs = require('./engine/powerplantreader.js'),
powerPlantjs = require("./engine/PowerPlant.js")
enginejs = require('./engine/engine.js'),
util = require('./engine/util.js'),
socketInterceptor = require('./engine/ai/socketinterceptor.js'),
dummyPlayer = require('./engine/ai/dummyplayer');
var failCallback = function (req, res, next, nextValidRequestDate) {
res.redirect('/'); // brute force protection triggered, send them back to the login page
};
var handleStoreError = function (error) {
console.error(error); // log this error so we can figure out what went wrong
};
// Start slowing requests after 5 failed attempts to do something for the same user
var userBruteforce = new ExpressBrute(bruteStore,
{
freeRetries: 10,
minWait: 5*60*1000, // 5 minutes
maxWait: 60*60*1000, // 1 hour,
failCallback: failCallback,
handleStoreError: handleStoreError
}
);
// No more than 1000 requests per hour
var globalBruteforce = new ExpressBrute(bruteStore, {
freeRetries: 1000,
attachResetToRequest: false,
refreshTimeoutOnRequest: false,
minWait: 60*60*1000, // 1 hour
maxWait: 25*60*60*1000, // 1 day 1 hour
lifetime: 24*60*60, // 1 day (seconds not milliseconds)
failCallback: failCallback,
handleStoreError: handleStoreError
});
// This exposes the session object to Pug (Jade) to all Pug templates
app.use(function(req, res, next) {
console.info("Before: " + JSON.stringify(req.session));
// If joining is set, the WebSocket connection likely altered the Session (and so deleted the value). We need to
// reload from the SessionStore to get the latest data.
if(req.session && req.session.joining){
console.info("Reloading session...");
// After loading, go ahead and proceed
req.session.reload(function(){
console.info("After: " + JSON.stringify(req.session));
res.locals.session = req.session;
next();
});
}
else{
res.locals.session = req.session;
next();
}
});
// routing
app.get("/", globalBruteforce.prevent, function(req, res) {
console.info("Request for home");
console.info(req.session);
let payload = {session: req.session};
Promise
.resolve(db.all('SELECT * FROM Games'))
.then(function(dbResult) {
console.info(JSON.stringify(dbResult));
if(dbResult) {
payload['games'] = dbResult;
res.render('home', payload);
}
else {
res.render('home', payload);
}
})
.catch(function(error) {
console.error(error);
});
});
app.get("/game/:gameId", globalBruteforce.prevent, function(req, res) {
console.info("Request for game");
console.info(req.session);
let gameId = req.params.gameId;
if(!validator.isInt(gameId, {min:1, allow_leading_zeroes: false})){
req.session.error = "Game id is not valid.";
res.redirect("/");
}
else {
console.info("Game requested: " + gameId);
// TODO: should instead just present a login page rather than this weird redirect
if(!req.session || !req.session.authenticated) {
console.info("no session data, going back home");
req.session.error = "You need to be logged in to play a game.";
res.redirect("/");
}
else {
req.session.joining = gameId;
res.sendFile(__dirname + '/gameclient.html');
}
}
});
app.post("/creategame", globalBruteforce.prevent, function(req, res) {
let hostUser = req.session.username;
let started = 0;
let maxPlayers = req.body.maxplayers;
if(!req.session || !req.session.authenticated){
req.session.error = "Need to be logged in.";
res.redirect("/");
}
else if(!validator.isInt(maxPlayers, {min:1, max:6, allow_leading_zeroes:false})){
req.session.error = "Valid number!";
res.redirect("/");
}
else {
Promise
// TODO: Should make sure the game name hasn't already been generated before.
.resolve(db.run('INSERT INTO Games (hostUser, maxPlayers, started) VALUES (?, ?, ?)',
hostUser, maxPlayers, started))
.then(function(dbResult) {
console.info("Result: " + JSON.stringify(dbResult));
let id = dbResult.stmt.lastID;
console.info("Id: " + id);
createGame(id);
if(activeGames.keys().length > 25){
// Putting a limiter on the number of total games that can be made to protect the server
// Really hacky for now, but should prevent Internet trolls scanning for vulnerable sites
// from doing too much damage.
process.exit();
}
res.redirect('/game/' + id);
});
}
});
app.post("/login",
globalBruteforce.prevent,
userBruteforce.getMiddleware({
key: function(req, res, next) {
// prevent too many attempts for the same username
next(req.body.username);
}
}),
function(req, res) {
let username = req.body.username;
let password = req.body.password;
if(!validator.isLength(username, USERNAME_RESTRICTIONS) || !validator.isLength(password, PASSWORD_RESTRICTIONS)){
req.session.error = "Invalid username and password.";
res.redirect('/');
}
else {
console.info("Attempted login by: " + username);
Promise
.resolve(db.get('SELECT password FROM Users WHERE username = ?', username))
.then(function(dbResult) {
if(dbResult) {
let retrievedPassword = dbResult.password;
return bcrypt.compare(password, retrievedPassword);
}
else {
return Promise.reject("INVALID_USER");
}
})
.then(function(matches) {
if(matches) {
req.session.authenticated = true;
req.session.username = username;
console.info("Session: " + JSON.stringify(req.session));
req.brute.reset(function(){
res.redirect('/');
})
}
else {
return Promise.reject("INVALID_USER");
}
})
.catch(function(err) {
console.error(err);
if(err === "INVALID_USER") {
req.session.error = "Invalid username and password combination";
res.redirect("/");
}
else {
req.session.error = "There was an error in logging in. Please try again.";
res.redirect("/");
}
});
}
});
app.get("/logout", function(req, res) {
req.session.authenticated = false;
delete req.session.username;
res.redirect('/');
});
app.post("/registeruser", globalBruteforce.prevent, function(req, res) {
console.info(req.body.username + " " + req.body.password + " " + req.body.email);
let username = req.body.username;
let email = req.body.email;
let password = req.body.password;
// Emails are optional (and even if I did take them, nothing is done with them anyway).
if(!validator.isLength(username, USERNAME_RESTRICTIONS) || (!validator.isEmpty(email) && !validator.isEmail(email))
|| !validator.isLength(password, PASSWORD_RESTRICTIONS)){
req.session.error = "Please enter valid information.";
res.redirect("/register");
}
else {
bcrypt.hash(password, 10)
.then(function(hash) {
return db.run('INSERT INTO Users (username, email, password) VALUES (?, ?, ?)',
username, email, hash);
})
.then(function() {
req.session.authenticated = true;
req.session.username = username;
res.redirect('/');
})
.catch(function(err) {
console.error("Registration Error: " + err);
res.session.error = "Error in registration. Try again.";
res.redirect("/register");
});
}
});
app.get("/register", function(req, res) {
res.render('register', {});
});
app.use('/clientScripts', globalBruteforce.prevent, express.static(__dirname + '/clientScripts'));
app.use('/data', globalBruteforce.prevent, express.static(__dirname + '/data'));
let citiesDef = new citiesjs.Cities();
let powerPlants = new powerPlantReaderjs.PowerPlantReader();
var activeGames = [];
// This exposes the session object from Express into Socket.IO
io.use(function(socket, next) {
sessionObject(socket.handshake, {}, next);
});
// connect to a player, listen
// TODO: There seems to be an issue with a player joining, but the tab not gaining focus in FF, and the player not initializing the game correctly.
io.on('connection', function(socket) {
let session = socket.handshake.session;
let gameId = session.joining;
let username = session.username;
console.info("Game attempting join: " + gameId);
let curGame = activeGames[gameId];
if(curGame && curGame.gameStarted) {
let player = curGame.getPlayerByUsername(username);
if(player !== undefined){
player.socket = socket;
reconnectPlayer(curGame, player, socket);
cleanJoiningSessionData(session);
}
else {
console.info("A player tried to join after the game started!?");
return;
}
}
else {
cleanJoiningSessionData(session);
processNewPlayer(socket, curGame, username);
}
});
function cleanJoiningSessionData(session) {
// No longer trying to join. Free up so the player can join another.
delete session.joining;
console.info(JSON.stringify(session));
session.save(function(err) {
if(err) {
console.info("error saving session: : " + err);
}
});
}
function reconnectPlayer(curGame, player, socket) {
socket.engine = curGame;
let comms = curGame.comms;
socket.uid = player.uid;
socket.emit(comms.SOCKET_USERID, player.uid);
socket.emit(comms.SOCKET_DEFINECITIES, citiesDef.cities);
comms.toAll(player.displayName + " has rejoined the game!");
console.info(player.uid + " [" + player.displayName + "] has rejoined the game.");
curGame.reconnectPlayer(player);
setupSocketBindings(socket, comms, curGame);
curGame.playersDisconnected.splice(curGame.playersDisconnected.indexOf(player.uid), 1);
if(curGame.playersDisconnected.length === 0) {
comms.toAll("All players reconnected, the game may now resume!");
}
else {
comms.toAll("Still waiting for " + curGame.playersDisconnected.length + " players to reconnect.");
}
}
function processNewPlayer(socket, curGame, username){
// For simplicity, bind the Engine object to the Socket
socket.engine = curGame;
let comms = curGame.comms;
let uid = 'player' + util.olen(curGame.players);
socket.uid = uid;
socket.emit(comms.SOCKET_USERID, uid);
let player = curGame.addPlayer(uid, username, socket);
socket.emit(comms.SOCKET_DEFINECITIES, citiesDef.cities);
comms.toAll(username + " has joined the game.");
console.info(username + " [" + socket.uid + "] has joined the game");
curGame.broadcastGameState();
setupSocketBindings(socket, comms, curGame);
return player;
}
function setupSocketBindings(socket, comms, curGame) {
// When the client emits sendchat, this listens and executes
// sendchat -> String
socket.on(comms.SOCKET_SENDCHAT, function(data) {
if(data[0] === '/') {
resolveCommand(socket, comms, curGame, data);
}
else if(data.trim().length !== 0) {
console.info("Chat message: " + data);
comms.toAllFrom(curGame.reverseLookUp[socket.uid], data);
}
});
// When the player does any action
// gameaction -> JsonObject
socket.on(comms.SOCKET_GAMEACTION, function(data) {
data.uid = socket.uid;
curGame.resolveAction(data);
});
// when the user disconnects
socket.on(comms.SOCKET_DISCONNECT, function() {
// TODO handle players leaving.
comms.toAll(curGame.reverseLookUp[socket.uid].displayName + " has left the game! We must wait for them to reconnect...");
socket.engine.addDisconnectedPlayer(socket.uid);
});
}
// handles user chat commands
function resolveCommand(socket, comms, curGame, data) {
console.info(data);
let command = data.substring(0, data.indexOf(' '));
let args = data.indexOf(' ') === -1 ? "" : data.substring(data.indexOf(' ') + 1);
if(command === "/name") {
let name = args;
console.info("Name received: " + name);
let player = socket.engine.reverseLookUp[socket.uid];
player.displayName = name;
socket.engine.broadcastGameState();
}
else if(command === "/addai"){
addNewAi(comms, curGame, args);
}
}
function addNewAi(comms, curGame, aiLevel){
if(aiLevel === "dummy"){
let socket = new socketInterceptor.SocketInterceptor(comms, comms.engine);
let dummy = new dummyPlayer.DummyPlayer(socket);
dummy.setup();
dummy.engine = curGame;
socket.client = dummy;
let name = "EZ-27";
dummy.setOwnPlayer(processNewPlayer(socket, curGame, name));
}
else{
comms.toAll("AI level not supported: " + aiLevel);
}
}
function createGame(id){
const comms = new communicationsjs.Communications(io);
let cities = new citiesjs.Cities(util.deepCopy(citiesDef.cities));
let powerPlantCopy = {};
for(let cost in powerPlants.powerPlants){
let plant = powerPlants.powerPlants[cost];
let copy = new powerPlantjs.PowerPlant();
powerPlantCopy[cost] = copy;
copy.createCopy(plant);
}
const engine = new enginejs.Engine(comms, cities, powerPlantCopy);
comms.setEngine(engine);
engine.engineId = id;
activeGames[id] = engine;
}
/**
* Given the current state of the game, which causes constant downtime/crashes, the previous games are still
* stored in the DB and referenced when the server restarts. Since there is also no game restore feature, or any
* automatic game pruning, it is easier to just purge all games.
*/
function removeDeadGames(){
db.run('DELETE FROM Games');
}
function readMaps(){
citiesDef.parseCityList("data/germany_cities.txt");
citiesDef.parseCities("data/germany_connections.txt");
}
function readPowerPlants(){
powerPlants.parsePowerPlants("data/power_plants.txt");
}
// In the case where a player somehow causes an uncaught exception, I would rather only the state of that game be
// corrupted than all other games killed/website go down.
process.on('uncaughtException', (err) => {
console.error("FATAL: Uncaught exception received: " + err);
});
// All setup is finished, start listening for connections.
Promise.resolve()
.then(() => db.open('../database.sqlite', {Promise}))
// NOTE: comment out the below after first-run if you want data to persist with each run in dev.
.then(() => db.migrate({force: (process.argv[2] === "debug" ? 'last' : false)}))
.then(() => removeDeadGames())
.then(() => readMaps())
.then(() => readPowerPlants())
.then(() => server.listen(process.env.PORT || 3000))
.catch((err) => console.error("WHAT " + err.stack));