0

I want to launch a js file in a js file with different permission. Just like this:

main.js (which gets started)


config = JSON.parse(require("./config.json")) // <- should be possible

console.log(config.authkey) // <- should be possible

require("./randomJSFile.js").run()

randomJSFile.js (which will be executed by main.js)


exports.run = () => {

 let config = JSON.parse(require("./config.json") // <--- this should not be possible, only the main.js file should have access to the config.json file

 console.log(config.authkey) // should not be possible

}

Does anyone know how to do something like that?

Xge
  • 450
  • 3
  • 14
  • Can I ask why you want to prevent access to the file like that, when you can simply just refrain from accessing the file anywhere else in your code? – awarrier99 Apr 09 '20 at 18:46
  • I did not code the `randomJSFile.js` file. I just want to get files from other devs, add it to my code, without need to review every file. – Xge Apr 09 '20 at 18:51
  • Ah I see. I don't know of a way to do exactly what you're asking but you could encrypt your config and then create a helper function in your main file that decrypts it and accesses properties. That way even if they do try to access the config, they won't get anything readable – awarrier99 Apr 09 '20 at 18:57

1 Answers1

1

Based on a snippet from this question here you could possibly override the require function to check for the filename, something like this:

const Module = require('module');
const originalRequire = Module.prototype.require;

Module.prototype.require = function() {
  if (!arguments.length || typeof arguments[0] !== 'string') return {};
  if (arguments[0].includes('config.json')) return {};
  return originalRequire.apply(this, arguments);
};

And then perform this override after you've already required the config in your main file, so you don't accidentally block yourself

awarrier99
  • 3,628
  • 1
  • 12
  • 19