Userscripts possible with highly closured javascript? - javascript

Okay, so I've been trying to do userscripts for certain websites. However, all of the websites I want to do userscripts for have packing that does not expose anything to me.
For example, I want to write userscripts for this website but it doesn't expose enough to me for anything interesting.
Is there any possible way to get through a closure and into it's context? I know Chrome Dev Tools lets you view contexts, but not via code.
Remember, in this scenario, I cannot just simply add something to global context as I do not control the code.

Is there any possible way to get through a closure and into it's context?
If you mean, can you get to the foo here:
(function() {
function foo() {
}
// ...code using foo...
})();
No, you can't, if it's not explicitly made available outside that scoping function.

Related

Javascript Eval and Function constructor usage

I'm currently experimenting on self replicating code. Out of love for the language I'd like to write it in javascript.
I'm working on a program that writes a function's code which in turn writes its function own code and so on. Basically, the desired process is this:
I manually create A function which returns code (which includes some randomness) and a numeric value (proposed solution to a problem).
I call this function a number of times, evaluate the results of each of those returned functions, and continue the process until I have code that is sufficiently good for what I'm trying to do.
Now, I have always been told how eval is evil, how never to use it and so on. However for my specific use case it seems like the Function constructor or eval are exactly what I'm looking for.
So, in short the question is:
Are eval/Function constructor indeed the best tools to use in my case? If so, I figured I'd use the Function constructor to scope the code executed, but is there a way to truly limit it from accessing the global scope? Also, what are some good practices for eval usage in my case?
I think I just figured out something I could use:
If I run my javascript code using node.js I can use the vm module which allows me to execute javascript code safely in a new context, and without letting the executed code have any access to the local or global scopes.
vm.runInNewContext compiles code, then runs it in sandbox and returns the result.
Running code does not have access to local scope. The object sandbox will be used as
the global object for code. sandbox and filename are optional, filename is only used in
stack traces.
You can see a full example here: vm.runInNewContext
This will allow me to eval code safely, and seems to be the safest way (I found) currently available. I think this is a much better solution than eval or calling the Function constructor.
Thank you everyone who helped.
Unfortunately I believe there is no way to prevent it from accessing the global scope. Suppose for example that in a web browser i evaled some code like this :
(function(window) {
eval(script);
)(null));
Any time the script tries to access window - it will get an error, since window is null. However someone who knew what they were doing could always do this :
var global = (function() {
return this;
}());
Since when you invoke a function in what Crockford calls the "function invocation style" then the this is always bound to the global variable.

Prevent javascript function to access DOM

Does anyone know if its possible to prevent a JavaScript function from accessing the DOM?
More info:
I am trying to create a "Threading" object for JavaScript, e.g. use the Worker object, fall back on setTimeOut when not available. Obviously the worker can't access the DOM, I would like to keep this standard.
Even more info:
One possible, but ugly possible solution (that I figured out just now):
function test(document, window)
{
}
But Nothing prevents the dev to access the dom from another function he calls within this function though - and you'll have to list the world of arguments.
No, that's not really possible in a normal browser environment.
You might be able to replace stuff like document.getElementById before calling the function and restoring it afterwards though... But I'm sure there are ways to get around this.
You could execute the function in a Web Worker. There is no access to DOM from a Web Worker.
But really, what are you trying to achieve?
Since your goal is to enforce conventions rather than to completely sandbox the JavaScript, you could indeed use a function with window, document and other DOM interfaces shadowed locally and then eval the third-party script:
(function test(window, self, top, document) {
'use strict';
eval(untrustedCode);
}());
Of course they still could access the real global object, but at least not directly.

How to save unauthorised manipulation in a JavaScript

I wrote a server-client app in javascript/HTML5 its supposed to allow clients to communicate/play a game in realtime using Node.js on the server side .
I know the use of private variables and etc . But how to prevent the whole game engine from unauthorised access via console api ?
As in how to write it in such a way that all variables fall in a private scope and once initiated they run pretty much independently without registering a single variable in the global scope so that nobody can mess the Game up!
From what i have researched i can do something like
function Game(){
// All declarations here
// Start a logic in here
}
and then calling it
new Game();
will do it ? but is there any better way to do the same ?
You can run a JavaScript application without registering any single variable, via an anonymous function:
(function() {
//local variables here.
})();
However, there is no reliable way to prevent cheating: One can easily analyse your code, and create fake AJAX requests. With the latest browsers, it's incredibly easy to capture your code.
With getters and setters, anyone can effectively intercept your functions. Using the deprecated arguments.callee.caller property, an attacker can read the source of the function call, effectively getting access to the closure as defined at the top of this answer.
Example:
var _alert = alert;
window.alert = null;
Object.defineProperty(window, 'alert', {
'value': function(m) {
console.log('Intercepted. Function source: ' + arguments.callee.caller);
_alert.call(this, m);
}
});
(function(){
var localVar = 'secret';
alert('Hi!');
})();
You can't trust anything that runs on the client's hardware, and that it. Even with the example you've given, anyone could easily modify and reload your script to cheat. Your best bet here, then is not to put any extra effort into this, but rather by writing your application normally and running it through a preprocessor like UglifyJS. The anonymous function pattern indicated by Rob in his answer is also common.
Also, about the MD5 hash thing - no, even if it's in "private scope" you can still view and modify it in a JavaScript debugger. The point here is that someone will always cheat because of the entire nature of the JavaScript execution environment - it's just that you'll need to make it as difficult as possible to cheat by obfuscating your code (obviously using a preprocessor) and other similar techniques.
JS code is always available, you may want to obfuscate your code to make cheating harder
All security can be circumvented with enough time. The goal of every security measure is to increase the time it takes to crack What Rob W says will help, but I suggest you also invest in obfuscation/minimization of your javascript which will have a much greater impact on the time and effort required to analyze it and create fake ajax requests than avoiding global variables.
However I concur that a javascript based application can never be very secure. The best you can hope for is "annoying to hack"
How can I obfuscate (protect) JavaScript?

How best for a Firefox extension to avoid polluting the global namespace?

I've been reading up on global namespace pollution when developing an extension for Firefox, and I want to avoid it as much as possible in my extension. There are several solutions, but generally, the solutions seem to center around only declaring one global variable for your extension, and putting everything in that. Thus you only add one extra variable to the global namespace, which isn't too bad.
As a brief aside, I have had a solution proposed to me that avoids putting any extra variables into the global namespace; wrap everything in a function. The problem here is that there's nothing to refer to in your XUL overlays. You have to declare elements in your overlays, and then in JS add a ton of addEventListeners to replace what would've been something like an oncommand="..." in XUL. I don't want to do this; I definitely want my XUL to include events in the XUL itself because I think it looks cleaner, so this isn't a solution for me. I therefore need at least 1 global variable for XUL oncommand="..." attributes to refer to.
So the consensus seems to be to have one (and only one) variable for your extension, and put all your code inside that. Here's the problem: generally, people recommend that that variable be named a nice long, unique name so as to have almost zero chance of colliding with other variables. So if my extension's ID is myextension#mycompany.com, I could name my variable myextensionAtMycompanyDotCom, or com.mycompany.myextension. This is good for avoiding collisions in the global namespace, but there's one problem; that variable name is long and unwieldy. My XUL is going to be littered with references to event handlers along the lines of oncommand="myextensionAtMycompanyDotCom.doSomeEvent". There's no way to avoid having to refer to the global namespace in my XUL overlays, because an overlay just gets added to the browser window's DOM; it doesn't have a namespace of its own, so we can't somehow limit our extension's variable scope only to our own overlays. So, as I see it, there are four solutions:
1. Just use the long variable name in XUL
This results in rather unwieldy, verbose XUL code like:
<statusbarpanel id="myStatusBar" onmousedown="myextensionAtMycompanyDotCom.onMyStatusBarClick();">
2. Add an element of randomness to a short variable name
We come up with a much nicer short variable name for our extension, let's say myExt, and add some random characters on to make it almost certainly unique, such as myExtAX8T9. Then in the XUL, we have:
<statusbarpanel id="myStatusBar" onmousedown="myExtAX8T9.onMyStatusBarClick();">
Clearly, this results in rather ugly and even confusing code as the random characters look odd, and make it look like some kind of temporary variable.
3. Don't declare any global variables at all
You could just wrap up everything in functions. This, of course, means that there is nothing to refer to in your XUL, and so every event must be attached to the XUL elements using addEventListener in your JavaScript code. I don't like this solution because, as mentioned above, I think it's cleaner to have the events referenced in the XUL code rather than having to search a ton of JS code to find which events are attached to which XUL elements.
4. Just use a short variable name in XUL
I could just call my extension's variable myExt, and then I get nice XUL code like:
<statusbarpanel id="myStatusBar" onmousedown="myExt.onMyStatusBarClick();">
Of course, this short name is much more likely to clash with something else in the global namespace and so isn't ideal.
So, have I missed something? Is there any alternative to the 4 solutions I proposed above? If not, what would be the best of the 4 (given that #3 is basically unacceptable to me), and why?
We use the JavaScript module pattern described in this blog post: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth. You can export the symbols that you want to use in your XUL handlers as described.
In addition, we use a reversed host name as the module name prefix to ensure that we control the namespace:
/* Set up the global namespace. */
if (typeof(com) == "undefined") var com = {};
if (!com.salsitasoft) com.salsitasoft = {};
/* Main namespace. */
com.salsitasoft.myExtensionGlobalStuffGoesHere = (function (my) {
return my;
})(com.salsitasoft.myExtensionGlobalStuffGoesHere || {});
Update: I changed this to pass com.salsitasoft.myExtensionGlobalStuffGoesHere into the closure if it already exists so that the namespace can be spread across multiple files.
Your functions have to "live" somewhere either way, so you cannot avoid to claim some kind of namespace. I also agree to your point that defining the event in the XUL is better than attaching them. So, I propose a hybrid between 3+4:
Find a namespace that is unique for your plugin yet as catchy as possible, for example "catchyseo".
Place all the code of your plugin and all variables inside this namespace. Use the anonymous function wrapper pattern like (have a look at some jQuery plugins as code examples):
window.catchyseo = (function(){var private = x; [...] })();
In your namespace, expose some event handlers which you can reference in your XUL.
This approach gives you the best of two worlds: you can define your events in XUL and you have a closed namespace without any global namespace pollution - except your one namespace variable.

How to debug code within Jquery closure?

I'm trying to become a better javascript developer by making use of established design patterns, avoiding polluting the global namespace, etc. While it's taking me some time to get used to the different style of coding, there are lots of good resources.
Where I'm really lagging is in my development practices. I'm used to being able to open Firebug / IE or Chrome console and invoking line by line tests and method calls. This doesn't seem possible with all design patterns (intentionally, I suppose).
How do serious JS developers debug code within closures, etc?
ie:
$(function() {
...
[declare lots of vars, functions, page load actions, etc.]
...
}
Do I really have to insert debug/break statements all over the place and then make sure they get wrapped/cleaned up before deployment?
var closure = (function(){function foo{...} return {'bar':foo}}());
now you can call something like closure.bar() ... and see what the result is
so long as you return an object that allows you to access the closure functions and vars you can test away...
sometimes I will write my inital code without closure
and make it all work... then wrap it in a namespace so I dont have to worry about it... but that is another approach
it really depends on your code style and how you develop
test early test often
best of luck

Categories