Multiplayer game NodeJS, HTML, JS - server/client side validation - javascript

My question is more related to validations of the movements in the game, the game is Checkers. I'm developing a Checkers game, in html, css, js, and nodeJS, the game will be multiplayer.
So my question is about the validation, what would be the best approach.
Right now all the validations (valid movement, etc) are done client side (of course must be server side).
My question is, what would be the best approach:
Having client side validation, if the validation is OK then send the validation to the server and validate it there if all is ok change turn for the next player, if not the server rejects the movement and the player have to do a valid movement.
No client side validation, just basics, all validation are done server-side.
Scenario 1: I think it's the best, because we don't rely that heavily on the server, if the movement client-side is wrong then it won't even send it to the server and if a player with bad intentions (modifying code) try to do bad movements there is the server with side validation.
Scenario 2: We rely more heavily on the server, it will consume more resources and will be slower for all online players overall, but it will be a little bit "faster" on the client side because there aren't as much validations as in scenario 1.
I think that Scenario 1 is the best approach because:
More security, client and server validations
Less lag for other player because only validated movements from the client will be validated in the server
Less Resources = Less infrastructure, so cheaper overall.
What's your opinion, or do you have a better approach?
Thanks all for reading.

This question is maybe a bit too open-ended and opinion-based for SO, but here goes:
Personally, I think having clients behave as "watchers" for the game server is ideal. The game server should be authoritative and do all the logic to ensure consistency.
I'm working on a networked JS game + engine right now and handle this as follows:
The server broadcasts 2 game states with timestamps to all clients. Each client then interpolates between state n and n+1. In that time, any user input is sent back to the server, which is then incorporated into states n+1 and n+2 which are sent on the next broadcast. When the clients reach n+1 in the interpolation, n+1 is corrected with the new pair of n+1 and n+2.
This means clients can experience maximum of 1 tick's worth of lag if an event was fired at the beginning of an interpolation and not broadcast to the other clients until the next state broadcast. This can be about 200 ms before it gets noticeable, but that's pretty tolerable in my experience.
I came to this method thanks largely to this incredibly useful set of articles by Gabriel Gambetta:
I. Client-Server Game Architecture
II. Client-Side Prediction & Server Reconciliation
III. Entity Interpolation
IV. Lag Compensation
Obviously I can't include all of the articles, but the gist of what I wrote above is in this image from the first article:

I would say senario 1 is better.
You need to use both types of validations. As a user clicks, show movement on the client side by javascript validation, and in the background send movement code to the server for validation so that player sitting on another can see it. Anyways you will have to send data to the server so that other player can see the movement of the player.
Add client-side validation also to prevent unnecessary request to the server and it will also increase waiting time for the player.

I usually prefer validation on server side for the following reasons:
Client is not loaded with validation burden.
In case validation fails, the back-end is aware thus, failures are logged centrally and you may decide on certain actions upon several failure cases. (post a message? send an email? see failures trending?)
Easier code debugging.
The client code is not trustworthy security wise.
Related to the game, you will have to send updates anyway so, your code will be more manageable if it is all server side and you may optimise various aspects of it.
tip: use socket.io, it is very easy to grasp, very reliable, supports server push messages

Related

Vue.js to Node.js Server: How can I secure my POST call?

I have a simple single page application (a game) written in Vue.js with a backend in Node.js, all hosted on Heroku. My frontend in Vue uses axios to do the api call to my backend, which uses express and mysql libraries to query my database and get high scores or post a new score.
I gave the finished game to my friends and they realized right away they could use postman or similar to do a simple post request and send a fake score, so I'd like to secure it.
I'm open to anything fairly simple, but I'd like to set a token that I can check in my Node.js if it matches, and if not, send a 403. I've tried setting an environment variable with a token, but on the front end ends up displaying that token in the resources if I inspect the element (if I use a .env file and then get the value). I've also tried my config.json files, but obviously there's no way to hide these values from anyone using inspect element. I tried checking the req.hostname but even when I send a request from postman, it returns a 200.
How can I secure my post request?
Problem
As others have pointed out, there is no generic way to generate information client side that cannot be forged. The problem being that no matter how complex the rules to generate this information (e.g. game scores must be prime numbers), somebody might isolate those rules and create arbitrary information (e.g. fake prime number scores without playing the game).
For games this often leads to input processing (client) and game rules (server) being split between client & server, making it impossible to isolate score generation from game rules. However this introduces latency and asynchronicity and requires heavy refactoring for client side games - three difficult issues.
Solution
There are scenarios where a different solution exists. Take chess: given a chessboard ask the client for the least possible number of moves until mate. The number of moves is the score and the lowest score wins. The client must send the specific moves and the server verifies the result. In other words the client side information is the entire input the player generates for the game.
As generic pattern this means: define the client side (score) information as entire game input. Record the entire input client side and re-run the game server side with this input. Verify the result.
Requirements:
Split input processing from game rules so that it can run with pre-defined input.
Implement equivalent server and client side game rules.
Eliminate any source of randomness! (E.g. use the same seed for the same random number generator or a server generated random number list)
You are close to this solution as you have wisely chosen one language for server and client, and Javascript represents numbers as plattform independent 64-bit floats (which avoids rounding errors). This solution avoids latency & asynchronicity, but does not allow multi-player games where atomic server side updates and coupled player input is needed.

How to make a network architecture without the server being authoritative

As a prototype i'm making a multiplayer paint game on a canvas using javascript and websockets. The conditions are that the server cannot generate the canvas in any way. All model logic happens on the client-side.
Right now i have the following setup:
1) When an input happens on the client side it is transferred to the server and saved. The server does a very simple validation check.
2) Every 15 ms (on the server) all inputs are sent to the clients and cleared. The clients render the input locally.
3) Every 200 ms each client send their version of canvas to the server where it is saved
4) Every 200 ms the server votes for the "right" version and send it backs to the clients where they update their canvas. The right version is stored on the server with a timestamp.
5) When a new client connects they get the most recent right version of the canvas from the server.
While this approach provides multiplayer paint with a persistent state, it also carries some issues. What is the right version and how do they vote? What happens when a client experience a lag for like 10 seconds and then send their version? Also, if each client is making constant local changes, the canvas for each client will never be quite the same, making it impossible? to find the correct version of the canvas because they all differ when sent to the server.
The question can be boiled down to: It is possible to make a reliant client-server architecture where the client does all the logic and the server only checks if the input is valid? Even if it entails more network traffic. And if so, what would be a good approch?
Upon further investigation I found some excellent documentation on the above problem.
Having a client-only network model can be described as a peer-exchange model and was actually what was used in age of empires 1+2. However, as Microsoft faced several issues getting the clients to run synchroniously (and small variations broke the game), I have decided on a server model instead with some shortcuts to actually enable the server to merge the models.

HTML5 game connecting to database safely (stopping manual JavaScript by user)

I'm using HTML, JQuery and PHP/MySQL. I understand for the most part that if I want to make this game safe then the server needs to do practically everything, but in some situations the game must tell the server to do things. In my case this is a RPG type setup, it will need to at times send a POST request to a PHP script via an Ajax call that updates, inserts or deletes from the database. Such as a player wins a battle and he's exp needs to be appended to, or a player takes a turn in a battle and it needs to work out the amount of HP taken off the other enemy and return it as well as updating the enemy's HP.
Lets say when the player clicks "Attack" and it runs a JavaScript function called playerMove('attack'), what stops the user going into their browser developer tools and running this function manually? Or using similar code on an alternative server and running cross site Ajax calls to the same public scripts on my server?
Is there any way around this problem? Even if I had a game that was made as a client side application (Like C# or whatever) wouldn't these problems still exist, but just harder for users to execute. Or would connecting to MySQL directly through C# be mostly safe if done correctly. But what about C# sending POST requests to PHP scripts, wouldn't that bring you back to the problem that as the scripts are public they could be POSTed to from other sources?
Basically, every time a player "attack" request comes in, the server needs to do at least the following:
Do basic validation on the data in the request.
Check that the subject player attack request is actually coming from the correct account.
Check that the player is currently in battle, it's his turn, the target of the attack is valid, the player doesn't have any status effects preventing attacking, etc. Any game logic that prescribes that the player can't attack right now.
Calculate the attack's effects.
Update the database.
Return the results to the client.
Return the results to all other clients, through long polling, WebSockets, etc.
Now, if the player tries to make the AJAX call when they shouldn't be able to, your server validation should prevent it. Remember, the client is all input/output and can't do any game logic without tons of code duplication between your JS and PHP.
Making a game in PHP, especially multiplayer, requires a ton of overhead and boilerplate. I'd honestly think about using another language/framework. For example, Meteor hooks up a lot of this stuff for you. Client, server, and database data are automatically synchronized. It also has latency compensation so the client can run the server code to get an expected result, and then update to the actual result whenever the server eventually responds. This would make your game feel like it's working in real time, while still giving the server the last say on whatever game logic happens.

voice activity detection within the browser

So this is a tricky one.
I wish to write a web application which records a word said by the user, and then sends the samples to the server side for processing.
The algorithm I have in mind is as follows:
start a recording session once the user has clicked on a button
wait for the user to have said a single word (assuming he know he's supposed to say a single word)
stop the recording once he said it
send the samples to the server, say using HTTP
process the signal on the server side
send some response back to the user.
There are several solution for Voice Activity Detection in Java,C#, and other high level languages I presume.
However, I wish this part would to be done on the Client side (otherwise, I'll have to send too much data from the client to the server which is highly inefficient) I.E in javascript and HTML5.
I'm not an experienced web developer, so my questions are:
Is this feasible? Is there a library for that (I haven't found any)?
What would be the best approach in approaching the problem?

webgame with simultaneous players

I have seen many webbrowser based games with players playing simultaneously.
Usually after waiting some time you can join a room where everyone is playing or you can play against one other player.
All those games use Flash.
How they achieve that?
It would be very complex to accomplice without Flash?
There are any toolkit (rails, etc) or plugin that provides this functionality?
Or it is just a matter of storing sessions and mixing them ?
Just a quick edit:
I am not interested in Flash or Silverlight solutions
There are a couple options for a JavaScript-only solution. They all involve AJAX of one form or another. (See my answer on AJAX and Client-Server Architecture with JavaScript for a larger breakdown.)
You have a choice between AJAX Polling, Long Polling, COMET, or the upcoming Web Sockets. The first step is to understand AJAX. Once you are comfortable with it, you can setup a polling system (with setInterval) to poll the server for new data every n miliseconds.
It's possible to do it without flash if you're comfortable with ajax and your game doesn't require rapid interactions between users. But in either case, I believe you have to poll the server. You might also want to read about comet http://en.wikipedia.org/wiki/Comet_(programming)).
Can you clarify what kind of game you would like to make? Turn based or real-time?
Since you're not interested in flash or silverlight solutions (which can use sockets and thus scale well with thousands of users) you can use javascript and use ajax to send and receive data.
Essentially you can use ajax like a socket by sending out input then letting the script "long poll" the server by having the server delay responding to it until it has data to send. The only problem is that you can only keep a connection open for so long before it times out (~30 seconds). This isn't usually a problem though since you're passing data back and forth frequently.
I'd research fastCGI (or so I believe it can work like this) and have a game server daemon respond to the requests directly. That way it can open a single database connection and process all of the clients quickly. While this isn't necessary it would probably scale really well if implemented correctly.
At the moment I've been making a proof of concept that's kind of naive. (Less naive than using the database as state and just using PHP scripts to update and receive the database's state. I should note though that for a only a few users and your own database this works rather well. I had 20 clients walking around at 100 ms updates. Sure it doesn't scale well and kills the database with 10 connections per client per second but it "works"). Basically the idea is that I have javascript generate packets and sends them to a PHP script. That PHP script opens a unix domain socket and forwards the data to a C++ daemon. Haven't benchmarked it though, so it's hard to tell how well it'll scale.
If you feel comfortable though I really do recommend learning flash and socket networking. Using Epoll on linux or IOCP on windows you can host hundreds of clients. I've done tests of 100 clients on a C# socket server in the past and it took less than 5% CPU handling constant streams of small packets.
Depends what technology you want to use. Flash can be used to create a game like that, so can Silverlight. They both use javascript to send mouse movements and other user input asynchronously to the server so that the game state can be updated on the server.
An article of flash game development:
http://www.brighthub.com/internet/web-development/articles/11010.aspx
Silverlight:
http://www.brighthub.com/internet/web-development/articles/14494.aspx
Java Applets are able to communicate with JavaScript (e.g. you want your UI to be HTML&CSS). So in theory you could implement your network code in a signed Java Applet. In this case you would not be limited to the plain client-server model.

Categories

Resources