Is it possible to restrict the scope of a javascri

2020-02-10 01:05发布

Suppose I have a variables in the global scope.

Suppose I wish to define a function which I can guarantee will not have access to this variable, is there a way to wrap the function, or call the function, that will ensure this?

In fact, I need any prescribed function to have well defined access to variables, and that access to be defined prior to, and separate from that function definition.

Motivation: I'm considering the possibility of user submitted functions. I should be able to trust that the function is some variety of "safe" and therefore be happy publishing them on my own site.

11条回答
forever°为你锁心
2楼-- · 2020-02-10 01:41

I verified @josh3736's answer but he didn't leave an example

Here's one to verify it works

parent.html

<h1>parent</h1>

<script>
abc = 'parent';
function foo() {
  console.log('parent foo: abc = ', abc);

}
</script>

<iframe></iframe>

<script>
const iframe = document.querySelector('iframe');
iframe.addEventListener('load', function() {
  console.log('-calling from parent-');
  iframe.contentWindow.foo();
});
iframe.src = 'child.html';

</script>

child.html

<h1>
child
</h1>

<script>
abc = 'child';

function foo() {
  console.log('child foo: abc = ', abc);
}

console.log('-calling from child-');
parent.foo();
</script>

When run it prints

-calling from child-
parent foo: abc = parent
-calling from parent-
child foo: abc = child

Both child and parent have a variable abc and a function foo. When the child calls into the parent's foo that function in the parent sees the parent's global variables and when the parent calls the child's foo that function sees the child's global variables.

This also works for eval.

parent.html

<h1>parent</h1>

<iframe></iframe>

<script>
const iframe = document.querySelector('iframe');
iframe.addEventListener('load', function() {
  console.log('-call from parent-');
  const fn = iframe.contentWindow.makeFn(`(
      function() {
        return abc;
      }
  )`);
  console.log('from fn:', fn());
});
iframe.src = 'child.html';

</script>

child.html

<h1>
child
</h1>

<script>
abc = 'child';

function makeFn(s) {
  return eval(s);
}
</script>

When run it prints

-call from parent-
from fn: child

showing that it saw the child's abc variable not the parent's

note: if you create iframes programmatically they seem to have to be added to the DOM or else they won't load. So for example

function loadIFrame(src) {
  return new Promise((resolve) => {
    const iframe = document.createElement('iframe');
    iframe.addEventListener('load', resolve);
    iframe.src = src;
    iframe.style.display = 'none';
    document.body.appendChild(iframe);  // iframes don't load if not in the document?!?! 
  });
}

Of course in the child above we saw that the child can reach into the parent so this code is NOT SANDBOXED. You'd probably have to add some stuff to hide the various ways to access the parent if you want make sure the child can't get back but at least as a start you can apparently use this technique to give code a different global scope.

Also note that of course the iframes must be in the same domain as the parent.

查看更多
何必那么认真
3楼-- · 2020-02-10 01:46

Run the code in an iframe hosted on a different Origin. This is the only way to guarantee that untrusted code is sandboxed and prevented from accessing globals or your page's DOM.

查看更多
男人必须洒脱
4楼-- · 2020-02-10 01:47

Using embedded Web Workers could allow to run safe functions. Something like this allows a user to enter javascript, run it and get the result without having access to your global context.

globalVariable = "I'm global";

document.getElementById('submit').onclick = function() {
  createWorker();
}


function createWorker() {
  // The text in the textarea is the function you want to run
  var fnText = document.getElementById('fnText').value;

  // You wrap the function to add a postMessage 
  // with the function result
  var workerTemplate = "\
function userDefined(){" + fnText +
    "}\
postMessage(userDefined());\
onmessage = function(e){console.log(e);\
}"

  // web workers are normally js files, but using blobs
  // you can create them with strings.
  var blob = new Blob([workerTemplate], {
    type: "text/javascript"
  });

  var wk = new Worker(window.URL.createObjectURL(blob));
  wk.onmessage = function(e) {
    // you listen for the return. 
    console.log('Function result:', e.data);
  }

}
<div>Enter a javascript function and click submit</div>
<textarea id="fnText"></textarea>
<button id="submit">
  Run the function
</button>

You can try these for example by pasting it in the textarea:

return "I'm a safe function";

You can see that it's safe:

return globalVariable;

You can even have more complex scripts, something like this:

var a = 4, b = 5;
function insideFn(){
    // here c is global, but only in the worker context
    c = a + b;
}
insideFn();
return c;

See info about webworkers here, especially embedded web workers: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Embedded_workers

查看更多
ら.Afraid
5楼-- · 2020-02-10 01:47

You can use WebWorkers to isolate your code:

Create a completely separate and parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps asynchronously in that context.

Here is a simple example:

someGlobal = 5;

//As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706
function getScriptPath(foo) {
  return window.URL.createObjectURL(new Blob([foo], {
    type: 'text/javascript'
  }));
}

function protectCode(code) {
  var worker = new Worker(getScriptPath(code));
}

protectCode('console.log(someGlobal)'); // prints 10
protectCode('console.log(this.someGlobal)');
protectCode('console.log(eval("someGlobal"))');
protectCode('console.log(window.someGlobal)');

This code will return:

Uncaught ReferenceError: someGlobal is not defined

undefined

Uncaught ReferenceError: someGlobal is not defined and

Uncaught ReferenceError: window is not defined

so you code is now safe.

查看更多
孤傲高冷的网名
6楼-- · 2020-02-10 01:47

EDIT: This answer does not hide the window.something variables. But it has a clean way to run user-defined code. I am trying to find a way to mask the window variables

You can use the javascript function Function.prototype.bind() to bind the user submitted function to a custom scope variable of your choosing, in this custom scope you can choose which variables to share with the user defined function, and which to hide. For the user defined functions, the code will be able to access the variables you shared using this.variableName. Here is an example to elaborate on the idea:

// A couple of global variable that we will use to test the idea
var sharedGlobal = "I am shared";
var notSharedGlobal = "But I will not be shared";

function submit() {
  // Another two function scoped variables that we will also use to test
  var sharedFuncScope = "I am in function scope and shared";
  var notSharedFuncScope = "I am in function scope but I am not shared";

  // The custom scope object, in here you can choose which variables to share with the custom function
  var funcScope = {
    sharedGlobal: sharedGlobal,
    sharedFuncScope: sharedFuncScope
  };

  // Read the custom function body
  var customFnText = document.getElementById("customfn").value;
  // create a new function object using the Function constructor, and bind it to our custom-made scope object
  var func = new Function(customFnText).bind(funcScope);

  // execute the function, and print the output to the page. 
  document.getElementById("output").innerHTML = JSON.stringify(func());

}

// sample test function body, this will test which of the shared variables   does the custom function has access to. 
/* 
return {
        sharedGlobal : this.sharedGlobal || null,
         sharedFuncScope : this.sharedFuncScope || null,
       notSharedGlobal : this.notSharedGlobal || null,
         notSharedFuncScope : this.notSharedFuncScope || null
 }; 
*/
<script type="text/javascript" src="app.js"></script>
<h1>Add your custom body here</h1>
<textarea id="customfn"></textarea>
<br>
<button onclick="submit()">Submit</button>
<br>
<div id="output"></div>

The example does the following:

  1. Accept a function body from the user
  2. When the user clicks submit, the example creates a new function object from the custom body using the Function constructor. In the example we create a custom function with no parameters, but params can be added easily as the first input of the Function constructor
  3. The function is executed, and its output is printed on the screen.
  4. A sample function body is included in comments, that tests which of the variables does the custom function has access to.
查看更多
Viruses.
7楼-- · 2020-02-10 01:52

In my knowledge, in Javascript, any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code.

Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions. Local scope in JavaScript is only created by functions, which is also called function scope.

Putting a function inside another function could be one possibility where you could achieve reduced scope ( ie nested scope)

查看更多
登录 后发表回答