I am currently writing a NodeJS command-line app. The app makes an API call and returns some data to the user. Given that this is a public API, the user requires an API token. This CLI will be installed globally on the user's machine via npm i -g super-cool-api-cli
.
The first time the user runs the CLI they are prompted for the token, and then I store it so that each subsequent time they run it they don't need to put it in. I have provided the user a way to reset it as well. I am storing it in the actual directory of my CLI module, which as stated is installed globally, and it looks something like this:
fs.writeFile( __dirname+'/.token.json', JSON.stringify( { "token": token }, null, 2 ), 'utf8', (e)=>{
// error handling and whatever
});
I name the file .token.json
, using a dot to at least make the file hidden by default.
I guess what I am asking is if there is a better/more secure way of storing sensitive information in a NodeJS command line app, that you would be running more than once. I thought about using things like environment variables but they seem to expire at the end of the process.
Security considerations are a skill I somewhat lack, but greatly desire to learn more about, so thank you in advance for your tips.
I think it's best to use the credential storage facilities provided by the OS for this sort of thing, assuming of course that each user has their own account on the machine. The only NPM package I know that handles that is node-keytar.
You can store your token in sqlite, and set a username/password for the sqlite.db file, here are the bindings for sqlite https://github.com/mapbox/node-sqlite3
The standard place to store such tokens is in the user's ~/.netrc
file (see specifications here). Heroku does this for example.
A nice consequence of this standard is that there exist libraries to read/write this file (such as netrc-rw).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With