Created
January 12, 2012 01:33
-
-
Save CrabDude/1597914 to your computer and use it in GitHub Desktop.
JS Sandboxing via Harmony Proxies and with()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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