Moving sensitive logic out of browser - javascript

I've made a nice little math quiz app in rails 5 that generates random math algebra problems to the user. All of the random variables and checking to see if user's answers are correct is done in the view with javascript. I want to move this logic to the backend so the user can't cheat with browser tools like inspect. Not sure where to put this in a rails app or how it would work?
Does it go in rails/lib or do I make an ajax call? The problems are not hard coded in a database, just randomly generated. So I need to generate some random numbers in the backend send to the view to display something like 3x - 2 = 5x + 12. And then have the user's answer checked against the solution for this random problem in the backend and send info back to front-end quiz form which is keeping track of score.

See Here is the basic rails folder structure and usage of each folder
Secondly, straight to the point You can write that kind of logic either in the controller(not recommended) or in the services(recommended)
I recommend to use services for that See Here why

Related

How could I create a one click hyperlink for websites like https://www.integral-calculator.com/ that automatically pastes into the Javascript box?

My web app generates Calculus I problems in Latex and non-Latex form.
I use these two websites to check my answers:
https://www.derivative-calculator.net/
https://www.integral-calculator.com/
E.g., I copy/paste the non-Latex form of the math problem log(v)/v**4 and put it into the Integral calculator website to understand the gaps in my knowledge that is stopping me from solving the problem independently on my own by hand writing/hand solving.
I am writing this post because I want to improve my web app and reduce the steps it takes for the user to check their answers to one of these calculators. Right now, the user has to copy the equation, click the website link, then paste the equation into the website Javascript box, and finally click "Go" to be able to see suggested steps to solve the problem.
I want to take some string the represents my equation (e.g. log(v)/v**4) and turn it into a one click hyperlink like https://www.integral-calculator.com/log(v)/v**4
A link such as this does not work, presumably because the website is using a JavaScript or MathJax feature.
You are correct in that, as these websites do not use URL parameters, you will not be able to generate a URL from within your app that auto-populates the required fields. Additionally, these websites do not appear to use any sort of publicly accessible API (they take form data and process the results on the server side).
My suggestion would be to use an existing public API to check results within your app. I believe Wolfram Alpha allows up to 2000 API calls per month for free.

architecture for get and store api request data

This is more of a architectural questions. An external platform had product and price information for let's say, books. There is an API available to get this information.
What I read is that it should be possible to create a function in Javascript and connect the Javascript to a page where you want to show the data on my own website. This would mean that for each page request an API-call is made. Since the requested information only changes once a day maximum this does not sound the most efficient solution.
Can someone advise a better solution? Something into the direction of a similar php or javascript function that does the request on the background, schedule an update and import the data into mysql? If so, what language would be most common.
I need the solution for a Joomla/php/mysql environment
Here's a simple idea - fetch and store results from the API (ones you think aren't gonna change in a day), either on disk, or in the database, and later use these stored results to retrieve what you otherwise would've fetched from the API.
Since storing anything in frontend JS across page reloads isn't easy, you need to make use of PHP for that. Based on what's given, you seem to have two ways of calling the API:
via the frontend JS (no-go)
via your PHP backend (good-to-go)
Now, you need to make sure your results are synced every (say) 24 hours.
Add a snippet to your PHP code that contains a variable $lastUpdated (or something similar), and assign it the "static" value of the current time (NOT using time()). Now, add a couple of statements to update the stored results if the current time is at least 24 hours greater than $lastUpdated, followed by updating $lastUpdated to current time.
This should give you what you need with one API call per day.
PS: I'm not an expert in PHP, but you can surely figure out the datetime stuff.
It sounds like you need a cache, and you're not the first person to run into that problem - so you probably don't need to reinvent the wheel and build your own.
Look into something like Redis. There's an article on it available here as well: https://www.compose.com/articles/api-caching-with-redis-and-nodejs/

Using HTML5 how can i send a simple string so I can see it?

So I have a game written in HTML5 which is all fine and dandy. At the end of the game there is a score the player recieves. I want my game to send me how many people have a score of atleast 100 or above. I need this statistic to balance out the game accordingly.
I was thinking I could make a txt file in a dropbox account and make the game edit the file.
Now pls dont tell me about security issues I am aware that they can change their score in the javascript console which sends false data.
How do I go about solving this simple task? I just need a way to tell how many people are getting a score of 100 or above from my game.
Thanks !!!
You will probably need to use a server-side language such as PHP to write to a remote file.
You will want to javascript something simple that when the the score is >100 (or whatever your threshold is) you would do a simple (probably ajax) query to a server.
While plenty of people are telling you to create a server-side app, if you do not already have a server, there are simpler ways to go. For example I believe google spreadsheets has an api or even better you could use something like Parse Data which is a free database-as-a-service with a simple javascript API and intended just for that purpose.
On the other hand, if you DO have a server but don't feel like setting up a full programming language to respond to API calls (which is NOT terribly hard by the way), you could use the server log. Whenever the user hits 100 points for example create a little invisible <img src="http://yoursite.com/i-got-over-100" height=1 width=1 style="position: absolute, left: -10000" /> then just check your server logs for how much i-got-over-100 was hit.

Make JS Code unreadable/heavy to "hack"

I want to write a little game where the users has to click on appearing elements/objects in a given time. In detail the objects appears in holes onto the ground and after x seconds the objects disappear. The gamer has y lifes and all clicks gets counted until he lost the game.
After that his highscore gets posted to a database (via form post or AJAX). Long story short how can I avoid the user faking his highscore before sending? The program language is JS.
I know its not possible to hide all the code and make it not hack-able. But I think it's enough if the code is so difficult that the user has to do a lot of work to understand where he has to intervent to send faked data.
Has anybody some ideas howto make the code as difficult as its possible?
Thanks in advance for any ideas :)
You should never really try to make your source code unreadable. It will make as great a headache for yourself than any obstruction to anyone modifying it.
That said, you could refactor all your variable names to complete gibberish and play with whitespace, but anyone seriously trying to understand your code could revert that in a decent text editor. To make it any more complex would take away from the efficiency of your program - otherwise you could fill it with useless calls to functions that don't do anything and strange incrementation of counters that the program does not depend on.
there are compressors that do exact the job you want! Some of them can be downloaded and used as offline tools, some are directly via web accessible:
http://javascriptcompressor.com
like jquery and others you can use your code to maintain the scripts and deliver a faster loadable packed version that is hardly readable
How about this:
Create two PHP pages, with one containing the game interface and the other containing the game's code. Program the first one so that it creates a one-time-use string that the tag will pass along as a parameter when it calls the JS code from the second one. Program the second one so it checks the validity of the string sent. If the string is valid, the script should output the JS code, then invalidate the string.
Then, when the user copies the URL of the script, pastes it into his browser, and hits "Return," all he sees is either a blank page or a "not authorized" message.

Server-side highscores for a Javascript-written game

I'm implementing a simple game in Javascript, and am interested in having an online highscores table for it, so that players can compete against one another. I've two concerns about this:
What is the simplest server-side program I need for this purpose? I don't need a full-fledged "web application", just something simple that gets POST requests with highscores, updates a database and sends back lists of scores. I'm familiar with Django. What are your suggestions?
How can I make the highscores table reasonably secure? I'm aware that making it bulletproof against competent and dedicated hackers is difficult, but I wouldn't want anyone with access to the Javascript sourcecode to be able to submit fictitious scores too simply. Any tools for this purpose?
It's going to be pretty hard to secure the high scores. I mean, it's not enough to ensure that it comes from your page, because if, say, the JavaScript function is submitHighScore(n) then they can always type javascript:submitHighScore(10000000) in the address bar on that page and have it work.
What comes to mind is perhaps some sort of hash function that generates specific codes that match certain levels in the game. When submitting the score it would also submit this hash, so users would have had to get to this level in order to get that equivalent score.
Another option would be for the game to pull in some kind of key that only works temporarily, so as you went along the key would change and then the score would be submitted to a central server intermittently.
Keep in mind that really determined individuals can always just track the data being sent to your data and decompile it.
You could go the Broderbund route and ask the player trivia questions which are validated server-side to ensure they really did pass the level they said they did...something like "What color was the monster in the previous level?"
To submit score securely, sign it (you'd also need to ensure that the score isn't faked before it's signed and sent, but that's another problem).
Hide a secret in JS code, and send highscore + hash(highscore + secret) to the server. The hash could be MD5/SHA1 — there are easy to find JS implementations.
Of course it won't stand anyone carefully analysing the JS code, but at least someone won't be able to submit fake highscore just by tampering with HTTP traffic.
On hiding stuff in JS:
You can't really hide it (it's ultimately futile like DRM), but you can try hard to obfuscate it and make debugging painful.
Don't put the secret as a literal in the source code - compute it at run time combining results of several functions, local and global-ish variables.
Minify all code, remove sourcemaps.
Add bits of code that don't do anything, but seem to be important, to make debugging more confusing.
Don't put anything in global scope, but do rely on shared mutable state by passing closures and arrays around.
Rely on Date and timers to cause race conditions to make your code produce wrong results if it's paused in the debugger (just don't make it too tight to allow it to run on slow machines).
If the game is deterministic (like a puzzle game), then users could submit highscore in form of a log of steps taken to win (user's input) that you'd replay on the server to calculate the score.
This would change attack from finding/emulating score-submitting function to witing AI or hacking the game itself to make it easier to play (but still within its basic rules).
1.) Any CGI script that can talk to a database and understand JSON, or other format of your choice, will do the work.
However, if you're familiar with Django, building your server on top of Django would be the most simple, in the sense of what you have to learn and how much application code you have to write. Seemingly simple CGI script can turn out rather complex if you write it from scratch.
I found django-piston to be a handy Django app to quickly write a REST-style API server. It supports JSON so it should be easy to interface with your JavaScript game.
2.) The most casual cracker will go for a replay attack and its variants: peek at the page source and execute a JavaScript function, intercept HTTP requests and resend it (should be easy with a Firefox add-on like Tamper Data).
To counteract the former, you can obfuscate the source code and HTTP body;
Minify the JavaScript code
Encode the message you send to the server with Base64 or other encoding algorithm
The latter can be prevented by requiring all update requests to include an one-time password ("session token" in the Wikipedia article) that was recently acquired from the server.
I am thinking about this myself. What seems to be the most reasonable solution to me is this:
1) Sessions, to disallow tampering with the scoretable outside the game.
2) Log every action in the game and send it to the score server. The server will then calculate if those actions actually give such score. If you also log the time spent playing the game, you can further minimize the chance of an attacker to bother himself enough to break your game. This will also enable you to make a replay script like Arcade servers with hi-score tables have and in case of a suspicious score, you can watch the replay and decide for yourself if the score is real. The cheater would have to use a clever bot to play your game - and unless you have a game for real prizes, noone will try that hard.
If the cheater won't even analyze your code, sessions will stop him. If he reads your code, he would quickly break anything similar to hashed scores, secrets, tokens and whatsoever. But if you make the game-logging script thorough enough, he will give up.
In answer to your question:
1.) This depends on your environment and coding preference. PHP, Python, ASP.NET are a few that come to mind. Sense you already know Python (from your profile) you can use a Python CGI script to do this or use one of the many frameworks for Python (Zope, Django, Pylons,...).
see: http://www.python.org/doc/essays/ppt/sd99east/index.htm
for info on Python CGI.
2.) A few tricks for security: (none or full-proof)
Hidden Text Box in HTML with encoded value that server checks to match a cookie to ensure high score comes from your page.
Server Script only accepts values from a specific domain
You could use a combination of one of the methods above, as well as simply requiring the user to be registered to be able to post high scores. Non registered users could view their current score compared to existing high scores, but in order to post your high score online, you must have already logged in with your registered account, or provide it when the app goes to update the score online.
A simple message along the lines of "Your high score is X, and ranks ### in the high score table. To post this score online, please register with us first".
The better I think, is to make the calculation of the score directly into the python files of your django app.
Instead of calculate it in the javascript file. You send the datas to compare with your data basis with a POST request, then you calculate the score and you store it in your data basis. Like this, you don't make circulate the score across the web to your servers. Which is completely safe because you are only doing local stuffs.

Categories