简体   繁体   中英

how to restrict global variables or functions in node js

how to restrict global variables and functions in node js?

like: require method

i want to limit use of require method. i don't want any node app to access "fs" in my node framework which i build on top of express, they can only require modules which i want them to. and also i want to restrict access to process, global scope .

suppose when i load any js library for any app

like:

var x=require('app1.js');

in my framework

then i want to make sure this app1.js cannot access filesystem using require("fs")

app1.js

var x=require("fs");
exports.hello=function(){
   console.log(typeof x.readSync);
}

i want this console to print undefined;

and in this sample

var x=require("helper.js");
exports.hello=function(){
   console.log(typeof x.hello);
}

i want this console to print function;

thanks in advance

I'd create a new function that will act like require.

requireSafe = function(param){
    if(!isAllowedLogic(param)) return null;
    else return require(param);
}

And when someone submits code, you append var require; at the top to prevent them to use the regular require . Or you search in their submission and only approve it if it doesn't contain require nor eval .

Why would you want to do that?

It is not possible to change the way require works, as it is a build-in node.js function.

Try this library, for a bit of detail of how its security works, from the README :

A Node.js subprocess is created by the Jailed library;

the subprocess (down)loads the file containing an untrusted code as a string (or, in case of DynamicPlugin, simply uses the provided string with code)

then "use strict"; is appended to the head of that code (in order to prevent breaking the sandbox using arguments.callee.caller);

finally the code is executed using vm.runInNewContext() method, where the provided sandbox only exposes some basic methods like setTimeout(), and the application object for messaging with the application site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM