Detect if HTML was edited - javascript

Is it possible to detect if - let's say - someone uses firebug to change parts of the website that's been loaded.
E.g. I got <a href="javascript:myfunc('hello')"> and someone changes that to <a href="javascript:myfunc('NOThello')">. Can I immediately detect this change somehow?
Thank you.

No, you cannot.
You could obviously write code to check to see if something was the way you wanted it to be, but guess what? People could change that very code to bypass the detection. Web pages are complete insecure. You cannot trust anything in them. They can be easily altered - any part of them can be altered including HTML, javascript, etc... And, using debuggers is not the only way to alter web pages - there are many different techniques including things like active proxies.
You MUST verify and check on the server anything that is being submitted to a server because you simply cannot trust its origin. For example, people use client-side javascript to validate data that is entered into forms all the time, but this is ONLY done to improve the user experience if something is entered incorrectly (so you can more easily tell the user something is wrong BEFORE the data is submitted to the server). All validation checking must also be done on the server to make sure that only valid data gets into your server.

Ah, right, you're just curious about how to do that!
I can't reproduce your test case, but here are the options I see:
using a recursive setTimeout or setInterval checking when the element has been altered, but that is highly slow and ugly
using mutation observers, and unset the changes
Florent

Related

How can I prevent someone from altering or avoiding my JavaScript logic when adding buttons to jQuery UI dialog?

I am using a jQuery UI dialog and I am adding buttons to the dialog in JavaScript based on some entitlements logic. (I pass in a boolean from my server-side AJAX call if I am entitled and then I show different buttons based on that flag.)
What concerned me is what is preventing someone from using developer tools like Firebug and putting a breakpoint on that line that does the check and either altering the flag or dragging to skip over that entitlements check.
So my question is specific to adding buttons onto a jQuery UI dialog (because its not like you can add the buttons from the server side since its a jQuery plugin), but I guess it highlights a more general point around any entitlements logic on the client side being "vulnerable". So if there are any general best practices around this point I would be interested (but still looking for an answer to my specific example).
NOTE: I am also doing a server-side entitlement check on POST as a backup, so I am still "protected" but I am still concerned about the point above.
Nothing prevents people from altering client-side code, it is inevitable.
You can, however, add buttons of the kind of "server-side", you just retrieve a string using the AJAX call, which happens to be a JavaScript function that adds buttons. And on the client side do eval() on that string which will execute the retrieved JS function and will add the buttons. Moreover, you can transmit your entire JavaScript code that way, so the client cannot skip anything since all is being executed in the eval().
A quick example:
Server-side function returns
string banana= "alert('test');";
return banana;
and client side does
eval(response.d);
Here is a theoretical example: FIDDLE
You cannot control what clients will do with your scripts, nor what requests they will make of your server. You must design your back-end API (not your JS client) to be the "gating mechanism" between the user and your system. It's best not to think of the JS as part of your system, but as a separate client that you ship as a reference implementation for your API.
But, if you wanted to at least make it difficult for users to mess with your code, you could minify and concatenate your JS scripts with something like Closure.
As the other person suggested, you cannot implement security on the client for exactly the reason you point out. You could use basic auth, or try setting up a token based approach.

Javascript Rule of thumb for delay length while using setTimeout() to allow a "loading" popup to appear

I'm using the setTimeout() function in javascript to allow a popup that says "loading" to be shown while I'm parsing some xml data. I found that at small enough delay values (below 10ms) it doesn't have time to show it before the browser freezes for a moment to do the actual work.
At 50ms, it has plenty of time, but I don't know how well this will translate to other systems. Is there some sort of "rule of thumb" that would dictate the amount of delay necessary to ensure a visual update without causing unnecessary delay?
Obviously, it'll depend on the machine on which the code is running etc., but I just wanted to know if there was anything out there that would give a little more insight than my guesswork.
The basic code structure is:
showLoadPopup();
var t = setTimeout(function()
{
parseXML(); // real work
hideLoadPopup();
}, delayTime);
Thanks!
UPDATE:
Turns out that parsing XML is not something that Web Workers can usually do since they don't have access to the DOM or the document etc. So, in order to accomplish this, I actually found a different article here on Stack Overflow about parsing XML inside a Web Worker. Check out the page here.
By serializing my XML object into a string, I can then pass it into the Web Worker through a message post, and then, using the JavaScript-only XML parser that I found in the aforementioned link, turn it back into an XML object within the Web Worker, do the parsing needed, and then pass back the desired text as a string without making the browser hang at all.
Ideally you would not ever have to parse something on the client side that actually causes the browser to hang. I would look into moving this to an ajax request that pulls part of the parsed xml (child nodes as JSON), or look at using Web Workers or a client side asynchronous option.
There appears to be no "rule-of-thumb" for this question simply because it was not the best solution for the problem. Using alternative methods to do the real meat of the work was the real solution, not using a setTimeout() call to allow for visual update to the page.
Given options were:
HTML 5's new Web Worker option (alternative information)
Using an AJAX request
Thanks for the advice, all.

jQuery: track multiple events in central location

Disclaimer: I am a designer with little jQuery knowledge. I will work with a JavaScript developer to realise this, but need to be able to write a detailed specification of my requirement.
I am looking to develop a platform which will track user behaviour via jQuery events API. Events, such as whether a user ‘points-and-clicks’ or tab’s to proceeding form fields will be scored, e.g. ‘point-and-click’ gets a -1 and tab gets a 2.
What is the best way of keeping track of all these event scores? My initial thought is an integer variable which increases and decreases in number depending upon user behaviour. The platform must also be able to:
be developed into a cookie
the value of the variable (if this is the best method) will inform which content to deliver to the viewstate via AJAX
I am happy to receive code snippets and/or written specification suggestions on how best to handle this.
Well, if your need is to be able to write a detailed specification of your requirements then copy/paste your question. It's ok like this.
Or make it more clear by removing your questionnings. If you're writing required specs, don't try to answer on how it should be done, just ask for what has to be done.
Track user behaviour via jQuery events API. Events, such as whether a
user ‘points-and-clicks’ or tab’s to proceeding form
fields.
You can add extra 'project management' infos like
date required
accessibility scope
some web development nice to write for a designer but useless for a developer stuff
budget
data chart / data flow
inputs/outputs

Avoiding content reload without use of frames/iframes

There are plenty of reasons to want to avoid <iframe>s (and indeed frames in general) but what are the best alternatives? (The intent here being to avoid full page reloads).
Facebook, for instance, seems to keep its top bar and side menu in tact (for the most part) and a full page reload incredibly rare.
Searching for explanations with little idea of what to use as search terms has rendered me little insight, so I thought it best to raise the question here. Is this all Ajax, or is there more to it than that?
AJAX
The more traditional approach is "AJAX". In a nutshell, your javascript code can request specific content from the server on a time (every x seconds) or when a user event happens (e.g. a button click).
A very basic implementation in jQuery would look something like:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
setInterval( "updateShouts()", 10000 );
This will update a div with id "shoutbox" every 10 seconds with whatever content is retrieved from latestShouts.php.
More advanced implementation would involve retrieving only data (not presentation) in a format like JSON or XML, and then updating the existing HTML values with the data that was received.
WebSockets
More recently, browsers have started supporting something called WebSockets. WebSockets allow you to keep a bidirectional connection open between the browser and the server, and it allows the server to push information to the browser without the browser requesting it.
This is more efficient in many ways; with the main reason being the fact that you don't have to waste server calls every x seconds to check if data is there. WebSockets allow you to display information from the server almost as soon as it becomes available.
I hope that helps..
Cheers!
Injecting partial content using ajax is your best and easiest bet - I recommend jquery too.

Ways to make Javascript code hacking / injection / manipulation difficult?

Are there ways to prevent, or make it difficult enough, for someone to inject Javascript and manipulate the variables or access functions? A thought I had is to change all var names randomly on each reload so the malware script would need to be rewritten every time? Or are there other less painful ways?
I understand that eventually someone will hack his way in, but I'd like to know ways to make it difficult to reproduce the action, so that people won't publish a bookmarklet or something similar for everyone to use. I don't care if experts find their way in the code, but I'd like it to be a bit more complex than javascript:d=0;
If you know ways to make hacking Javascript a bit more difficult, please write those.
Accept that your javascript will be "manipulated" and make provision at the server side. There's fundamentally nothing you can do to stop people tinkering with the client.
You can write your JS to use only private methods and variables in a self-executing function. For example, the following code leaves no sign of itself in the global namespace for anyone to monkey with.
(function(){
var x = 1;
var y = 2;
var z = "A am z";
var clickHandler = function() {
alert('You clicked the body');
};
document.getElementsByTagName('body')[0].addEventListener('click',clickHandler,true);
}());
[EDIT]
The above code is susceptible to a user overwriting any globally available objects, methods, events or properties you are using (in this case, document, getElementsByTagName and addEventListener), so if you are truly paranoid you can copy these to your function scope before the page has loaded and the user has a chance to overwrite them. Using addEventListener is a good idea because unlike the event body.onclick, it cannot be removed or overwritten from outside the function.
Any user that will really want to tamper with the client will be able to. The code is on his machine. Even if you obfuscate the client side code, there are tools out their that will help someone deobfuscate the code back in a second.
What you need to think about though is making the site safe on the server, and safe for other users as well.
This means (as a minimum):
Checking/Validating every request and input parameters on the server so Users won't be able to alter any server side data by triggering 'hacked' client side functions you wrote.
Check all data that you output to the screen that was originated from user input. Other users might have inserted client side scripts that are dangerous for your site, and especially dangerous to the other users on your site. (If you're using .net then check out the AntiXSS library)
Obfuscation and minification should make it a good bit more difficult to hack, but I agree with spender.

Categories

Resources