Search code examples
nashorn

Remove Globals from Nashorn


Is there a way to remove access to globals in Nashorn short of

$ENV=undefined

?

I have done some searching, but I am unable to see anything other than how to use globals.

Also, is there a list of arguments/flags I can pass into the script engine? I am currently doing --no-java, but I cannot find a comprehensive list anywhere.

Any help is appreciated.


Solution

  • You can get a list of command-line options via jjs -help.

    I don't know for sure about removing globals, but I doubt it. Nashorn uses a Global class that represents the ECMAScript global object, as described here.

    The default context's ENGINE_SCOPE is a wrapped instance of ECMAScript "global" object - which is the "this" in top level script expressions. So, you can access ECMAScript top-level objects like "Object", "Math", "RegExp", "undefined" from this scope object. Nashorn Global scope object is represented by an internal implementation class called jdk.nashorn.internal.objects.Global.

    That Global class has a bunch of the base ECMAScript plumbing baked into it in an immutable way, as without it javascript simply wouldn't work (no Object or Function prototypes, for instance). That page states that attempts to use an alternative object as the global will result in the engine placing your custom 'global' object into a new Global instance. Trying to run Javascript without that global plumbing simply wouldn't work.

    Now if what you want to do is limit the Java classes available to a script, that's relatively straightforward (though not as straightforward as I wish it was).

    ClassFilter filter = new ClassFilter() {
        @Override
        public boolean exposeToScripts(String name) {
            // This would disable all Java classes
            return false;
        }
    };
    ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(filter);
    

    The main downside here is that the ClassFilter and getScriptEngine(ClassFilter) methods aren't part of the javax.scripting API, and you have to access the Nashorn-specific classes in the jdk.nashorn.api.scripting package directly.