Reputation: 10589
Imagine you have a simple JavaScript function like this:
function something() {
console.log("You called that function");
}
You can ofcourse include the Script file into your HTML file and call the function. The problem is that JavaScript is clientside and so everybody can call this function using the google chrome adress input or the firefox console for example.
How can i prevent that? If you implement a game or something where user can be in a scorerlist or something it is easy to manipulate this scorerlist for example.
Upvotes: 2
Views: 309
Reputation: 2131
This is why you add backend code on your server side to test for anyone cheating. There is nothing stopping them in a JavaScript game from injecting functions and modules.
Rule #1 for any online multiplayer games: Never trust the client.
Rule #2 for any online multiplayer games: Never trust the client.
This is why most JavaScript games rely heavily on a server state, to prevent cheats. So you would have to make ALL of your computations server side.
Some things you could do:
check client reaction time to changes on the server, check for too many too fast reactions.
Store the games internal state sever side and check the input send by clients on the server.
You can also obfuscate Javascript. How can I obfuscate (protect) JavaScript?
You would also have to go the Diablo 3 Path.
Upvotes: 1
Reputation: 4121
Actually, you will need some server validation if you want to make things safe. Everything what you do in JS, is unsafe and can be "accessed" by a final user. Anyway, if you want to have some function that aren't usable from the console, you could think about using Module Pattern and create your functions inside your namespaces and only make public the one you want. For example, you could do something like:
var GAME = (function(){
var private1, privatePublic;
private1 = function() {
//This won't be accessible from outside
};
privatePublic = function() {
console.log("public");
//This will be accessible from outside because i am going to return it
};
return {
getPrivatePublic: privatePublic
}
}());
GAME.getPrivatePublic(); // will log "public"
GAME.private(); // Will throw error
This way, you are "hiding" your code from being used from the console. Anyway, as mentioned in my first lines, it is not safe and everything can be accessed by an user who has JS knowledge.
Upvotes: 2
Reputation: 156948
How can I prevent that?
You can't.
Everything you do client side must be considered unsafe. Never assume something is checked or valid because it passed some client side checks. You should always use server side validation for every check you do client side. Always!
If you implement a game or something where user can be in a scorerlist or something it is easy to manipulate this scorerlist for example.
Yes, on that client. So why do you care? The scores should be calculated server side, so changing the UI client side doesn't help anything.
Let Jon Skeet get scared!
Upvotes: 8