Reputation: 111
I'm looking to create a permission-based plugin system for a project in Node. For ease of writing, and for other reasons, I'd like to allow myself to call a plugin with:
var plugin = require('plugin');
Here's the trick, I want to force plugin
to use my permissions api system, but I want the plugin writer to be able to do something like:
var library = require('library');
What this would require, is the ability to create my own require()
method, and pass it to the plugin/module so they are using my method without any more work. My method would (primitively) work like this:
function myRequire (module) {
if(meetsPermissions) return require(module);
throw 'You don't have the necessary permissions;
}
Is this possible in Node?
Upvotes: 3
Views: 1776
Reputation: 203359
You can override the default loader in require.extensions
. However, this is deprecated so it might be removed from Node.js at any time.
For example:
var jsloader = require.extensions['.js'];
require.extensions['.js'] = function(module, filename) {
if (meetsPermissions(module)) return jsloader.apply(this, arguments);
throw new Error("You don't have the necessary permissions");
};
Some caveats (besides from the deprecation):
meetsPermissions()
should be relatively fastutil
, http
, etc)Another possible solution could be running all the code in a sandbox using the vm
module. There are various higher-level modules that offer this, like node-sandboxed-module
.
Upvotes: 3