Skip to content

Instantly share code, notes, and snippets.

@CrabDude
Created January 12, 2012 01:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CrabDude/1597914 to your computer and use it in GitHub Desktop.
Save CrabDude/1597914 to your computer and use it in GitHub Desktop.
JS Sandboxing via Harmony Proxies and with()
// in new iframe
var whitelist = {
// add whitelisted globals
};
var handler = {
// Fundamental traps
getOwnPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(whitelist, name);
// a trapping proxy's properties must always be configurable
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
getPropertyDescriptor: function(name) {
var desc = Object.getPropertyDescriptor(whitelist, name); // not in ES5
// a trapping proxy's properties must always be configurable
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
getOwnPropertyNames: function() {
return Object.getOwnPropertyNames(whitelist);
},
getPropertyNames: function() {
return Object.getPropertyNames(whitelist); // not in ES5
},
defineProperty: function(name, desc) { },
delete: function(name) { return false; },
fix: function() {
// As long as obj is not frozen, the proxy won't allow itself to be fixed
return undefined; // will cause a TypeError to be thrown
},
// derived traps
has: function(name) { return true;},
hasOwn: function(name) { return true;},
get: function(receiver, name) { return whitelist[name]; },
set: function(receiver, name, val) { return false; }, // don't allow
enumerate: function() {
var result = [];
for (name in whitelist) { result.push(name); };
return result;
},
keys: function() { return Object.keys(obj) }
};
var proxy = Proxy.create(handler);
(function() {
with(this) {
// untrusted code here
}
}).call(proxy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment