Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How restrict access to apis in node.js javascript?

I did a little research and couldn't find anything that makes my case success.

So, I'm loading .js from external scripts with require(..), each script exports a function ..

main.js

var main=10;
var mod1 = require("./mod1.js");

mod1.js

module.exports=function(){
 console.log('loaded');
 var net=require('net'); // i don't want it to be able to require certain node.js apis
 net.create...; 
}

I saw some ways where a .json file declares the permissions and if so it grants access to script. How can something like that be achieved for core node.js apis?

like image 993
Gntem Avatar asked Oct 18 '13 07:10

Gntem


People also ask

How do I restrict access to API?

Set an application restriction for an API keyGo to the Credentials page. Select the API key that you want to set a restriction on. The API key property page appears. Under Key restrictions, select Application restrictions.

How do I limit API calls in node JS?

Copy and paste the following code inside this file: // src/middlewares/rateLimiter. js import rateLimit from 'express-rate-limit'; export const rateLimiterUsingThirdParty = rateLimit({ windowMs: 24 * 60 * 60 * 1000, // 24 hrs in milliseconds max: 100, message: 'You have exceeded the 100 requests in 24 hrs limit!


1 Answers

Depending on what exactly you want, you might be able use the vm module (which is built-in to Node) as a sort of sandbox thing:

var vm = require('vm');
var fs = require('fs');

var safe_require = function(mod) {
  var code    = fs.readFileSync(require.resolve(mod));
  var sandbox = {
    console : console,
    module  : {},
    require : function(mod) {
      // as a simple example, we'll block any requiring of the 'net' module, but
      // you could implement some sort of whitelisting/blacklisting for modules 
      // that are/aren't allowed to be loaded from your module:
      if (mod === 'net') {
        throw Error('not allowed');
      }
      // if the module is okay to load, load it:
      return require.apply(this, arguments);
    }
  };
  vm.runInNewContext(code, sandbox, __filename);
  return sandbox.module.exports;
};

var mod = safe_require('./mod1');

(as you can see, any built-in functions of Node, like console, that you want to use in the modules that are safe_require'd need to be passed in the sandbox object)

like image 59
robertklep Avatar answered Sep 30 '22 18:09

robertklep