Skip to content

Commit

Permalink
add sandbox.js
Browse files Browse the repository at this point in the history
  • Loading branch information
janl committed Oct 3, 2013
1 parent 12763ee commit ba6bdae
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions NOTICE
Expand Up @@ -189,3 +189,7 @@ This product also includes the following third-party components:
* share/doc/src/templates/couchdb/domainindex.html

Copyright 2007-2011 by the Sphinx team

* sandbox.js https://github.com/KlausTrainer/sandbox.js

(c) 2013 Klaus Trainer
1 change: 1 addition & 0 deletions license.skip
Expand Up @@ -110,6 +110,7 @@
^src/couchdb/priv/couchspawnkillable
^src/couchdb/priv/stat_descriptions.cfg
^src/couchjs-node/package.json
^src/couchjs-node/sandbox.js
^src/couchjs-node/README.md
^src/erlang-oauth/.*
^src/couch_dbupdates
Expand Down
40 changes: 40 additions & 0 deletions src/couchjs-node/sandbox.js
@@ -0,0 +1,40 @@
// from https://github.com/KlausTrainer/sandbox.js
exports.runInSandbox = function(src, ctx, whitelist) {
var vm = require('vm'),
sandbox;

if (ctx && ctx.require) {
whitelist = whitelist || [];
var insecureRequire = ctx.require,
module = require("module"),
oldModulePrototype = module.prototype;

var secureRequire = function(moduleName) {
if (whitelist.indexOf(moduleName) == -1) {
module.prototype = oldModulePrototype;
throw new Error("'" + moduleName + "' is not whitelisted");
} else {
var requiredModule = insecureRequire(moduleName);
module.prototype = oldModulePrototype;
return requiredModule;
}
};

module.prototype = {
require: secureRequire,
load: module.prototype.load,
_compile: module.prototype._compile
};

module._cache = {};

ctx.require = secureRequire;
sandbox = Object.freeze(vm.createContext(ctx));
ctx.require = insecureRequire;
} else {
sandbox = Object.freeze(vm.createContext(ctx || {}));
}

return vm.createScript('(function() {"use strict"; return ('
+ src + ')()}())').runInContext(sandbox);
};

0 comments on commit ba6bdae

Please sign in to comment.