Electrolysis compatibility shims doesn't work with evalInSandbox - firefox

We have a rather old XUL extension which we want to make sure works with Electrolysis. We will eventually migrate it to the WebExtensions API, but for now we want to use the compatibility shims.
We can access content stuff (using window.content for example) in the some of our scripts (e.g, the overlay scripts). However, our extension also load some scripts using evalInSandbox. It look something like this:
var sandbox = Components.utils.Sandbox(Components.classes["#mozilla.org/systemprincipal;1"].createInstance(Components.interfaces.nsIPrincipal), {
sandboxPrototype: window,
wantXrays: false
});
// ...
Components.utils.evalInSandbox(script, sandbox, url, 0);
We don't seem to be able to access window.content on the scripts loaded in the sandbox. It seem like the shims don't work in this case. Is this a bug, or is it by design?
Thanks

Your sandboxPrototype is wrong, you are setting it to the nsIDOMWindow, set it to the aNSIDOMWindow.gBrowser.tabContainer.childNodes[tab_index_goes_here].contentWindow
see this example on mdn: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.Sandbox#Example
also here is how to load in a script as file rather then doing evalInSandbox:
https://github.com/Noitidart/modtools

Related

How to avoid duplicate default configuration for Firefox add-on?

I'm trying to implement some customization for a WebExtensions add-on, but I'm running into code duplication: both the options UI script and the content script need to know the default values for each setting, and AFAIK I can't expect either of them to be run before the other. Is there an elegant way to ensure that the local storage is initialized before either of them run?
Try this. If the storage is never set, the default-value-1 and default-value-2 will be used.
let settings = await browser.storage.local.get({
option1: "default-value-1",
option2: "default-value-2"
});
See more here: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/StorageArea/get

can you load external executable javascript from a firefox extension?

Does anyone know if there is a way to load any external executable javascript from a firefox add-on extension? I looked into scriptloader.loadSubScript, but it appears that it can only load from a local resource.
Any help would be appreciated.
You can always xhr for a file, save the contents to disk, then use scriptloader.loadSubScript with an add-on
this would violate the AMO policies though, so you wouldn't be able to upload the add-on to http://addons.mozilla.org
As #erikvold already pointed out, doing so would be a security hazard AND it also violates AMO rules (because it is a security hazard).
Consider your server gets compromised, or there is a way to MITM the connection retrieving the remote script (TLS bugs anyone :p), or you sell your domain and the new owner decides to ship a script to collect credit card information straight from a user's hard disk...
However, it is possible to run a remote script in an unprivileged environment, much like it would run in a website.
Create a Sandbox. The Sandbox should be unprivileged, e.g. pass an URL in your domain into the constructor.
Retrieve your script, e.g. with XHR.
Evaluate your script in the Sandbox and pull out any data it might have generated for you.
This is essentially what tools like Greasemonkey (executing user scripts) do.
Creating and working with Sandboxes in a secure fashion is hard, and the Sandbox being unprivileged prohibits a lot of use cases, but maybe it will work for your stuff.
Try using Components.utils.import .
Example :
const {Cc,Ci,Cu} = require("chrome");
Cu.import("url/path of the file");
Note :
js file which uses DOM objects like window, navigator, etc. will return error saying "window/navigator is undefined". This is simply because the main.js code does not have access to DOM.
Refer this thread for more information.

Where should utility functions in a Firefox Extension be placed

As I'm writing a Firefox XUL Extension I find that I want to share some functionality (the business logic) across the whole extension. What would be the best place to store this?
Can I create some sort of library (javascript) file which always gets loaded first?
You most likely want to create a JavaScript code module. You can use Components.utils.import() to load it:
Components.utils.import("chrome://myaddon/content/utils.jsm");
And in utils.jsm you define which symbols should be imported by that statement, e.g.:
var EXPORTED_SYMBOLS = ["Utils"];
var Utils = {
};
The module will be loaded when it is first used and stay in memory after that - there will be only a single module instance no matter how many places on your extension use it. Note that I used a chrome:// URL to load the module, this is supported starting with Firefox 4. Documentation recommends using resource:// URLs which is cleaner because modules don't actually have anything to do with the user interface - still, using a chrome:// URL is often simpler.

Toggle javascript support programmatically without restarting firefox

The problem: toggle javascript support without restarting firefox (nor resorting to different driver) during cucumber test run.
If Firefox's prefutils were exposed to javascript in a web page, that would make it possible. But it is not the case.
So, is there a plugin that does it? Or is there another way to solve the problem? Or is there a good tutorial (that highlights the exposing bit) on how to make such a plugin?
Edit
On a second thought, how would javascript be of any help once it is disabled? Probably the whole idea is a bit screwed.
I assume that your tests run with normal web content privileges. In that case, they aren't going to be able to affect browser settings such as whether JavaScript is enabled (I assume that's what you mean by "toggle JavaScript support").
I'd implement a simple XPCOM component with a method to turn JS support on and off (by setting the appropriate pref). You can expose it as a JavaScript global property so that your tests can access it. See Expose an XPCOM component to javascript in a web page for more details. Package your component in an extension and make sure it is installed in the Firefox instance where your tests are running.
If you want to access the preferences API directly from your content script, you can add the following prefs to Firefox, either in about:config or by adding the following lines to prefs.js in your profile directory:
user_pref("capability.principal.codebase.p1.granted", "UniversalXPConnect UniversalBrowserRead UniversalBrowserWrite UniversalPreferencesRead UniversalPreferencesWrite UniversalFileRead");
user_pref("capability.principal.codebase.p1.id", "http://www.example.com");
user_pref("capability.principal.codebase.p1.subjectName", "");`
user_pref("signed.applets.codebase_principal_support", true);
Replace www.example.com with the domain that you want to grant the privileges to. Also add this line to your JS code before you call the preferences API:
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
A local file (something loaded from file:///) is allowed to request additional privileges. Normally you would get a prompt asking whether you want to allow access - you can "auto-accept" the prompt by adding the following lines to prefs.js in the Firefox profile:
user_pref("capability.principal.codebase.p0.granted", "UniversalXPConnect");
user_pref("capability.principal.codebase.p0.id", "file://");
user_pref("capability.principal.codebase.p0.subjectName", "");
You page can then do:
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var branch = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
branch.setBoolPref("javascript.enabled", false);
This will definitely work if your page is a local file. Judging by the error message however, you are currently running code from about:blank. It might be that changing capability.principal.codebase.p0.id into about:blank or into moz-safe-about:blank will allow that page to get extended privileges as well but I am not sure.
However, none of this will really help if JavaScript is already disabled and you need to enable it. This can only be solved by writing an extension and adding it to the test profile. JavaScript in Firefox extensions works regardless of this setting.
That means you need Javascript to toggle enabling or disabling Javascript.
function setJavascriptPref(bool) {
prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
prefs.setBoolPref("javascript.enabled", bool);
}

How can a bookmarklet access a Firefox extension (or vice versa)

I have written a Firefox extension that catches when a particular URL is entered and does some stuff. My main app launches Firefox with this URL. The URL contains sensitive information so I don't want it being stored in the history.
I'm concerned about the case where the extension is not installed. If its not installed and Firefox gets launched with the sensitive URL, it will get stored in history and there's nothing I can do about it. So my idea is to use a bookmarklet.
I will launch Firefox with "javascript:window.location.href='pleaseinstallthisplugin.html'; sensitiveinfo='blahblah'".
If the extension is not installed they will get redirected to a page that tells them to install it and the sensitive info won't get stored in the history. If the extension IS installed it will grab the information in the sensitiveinfo variable and do its thing.
My question is, can the bookmarklet call a method in the extension to pass the sensitive info (and if so, how) or can the extension catch when javascript is being called in the bookmarklet?
How can a bookmarklet and Firefox extension communicate?
p.s. The alternative means of getting around this situation would be for my main app to launch Firefox and communicate with the extension using sockets but I am loath to do that because I've run into too many issues over the years with users with crazy firewalls blocking socket communication. I'd like to do everything without sockets if possible.
As far as I know, bookmarklets can never access chrome files (extensions).
Bookmarklets are executed in the scope of the current document, which is almost always a content document. However, if you are passing it in via the command line, it seems to work:
/Applications/Namoroka.app/Contents/MacOS/firefox-bin javascript:alert\(Components\)
Accessing Components would throw if it was not allowed, but the alert displays the proper object.
You could use unsafeWindow to inject a global. You can add a mere property so that your bookmarklet only needs to detect whether the global is defined or not, but you should know that, as far as I know, there is no way to prohibit sites in a non-bookmarklet context from also sniffing for this same global (since it may be a privacy concern to some that sites can detect whether they are using the extension). I have confirmed in my own add-on which injects a global in a manner similar to that below that it does work in a bookmarklet as well as regular site context.
If you register an nsIObserver, e.g., where content-document-global-created is the topic, and then unwrap the subject, you can inject your global (see this if you need to inject something more sophisticated like an object with methods).
Here is some (untested) code which should do the trick:
var observerService = Cc['#mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
observerService.addObserver({observe: function (subject, topic, data) {
var unsafeWindow = XPCNativeWrapper.unwrap(subject);
unsafeWindow.myGlobal = true;
}}, 'content-document-global-created', false);
See this and this if you want an apparently easier way in an SDK add-on (not sure whether SDK postMessage communication would work as an alternative but with the apparently same concern that this would be exposed to non-bookmarklet contexts (i.e., regular websites) as well).

Resources