Dave Lunny
Dave Lunny

Reputation: 770

Securely store data in a Node CLI app

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.

Upvotes: 11

Views: 3737

Answers (4)

Thomas Vanderstraeten
Thomas Vanderstraeten

Reputation: 186

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).

Upvotes: 1

New Alexandria
New Alexandria

Reputation: 7324

A semi-conventional location to store secrets, like keys, is the .ssh directory.

  • It often has ACLs restricted to the user, and
  • your file would follow the related ACL pattern
  • the typical files of this directory include unencrypted secret keys. Nothing prevents you from further encrypting.
  • a dot-file in there should not get in the way of typical uses of the directory.

Upvotes: 0

Vadim Macagon
Vadim Macagon

Reputation: 14837

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.

Upvotes: 7

Eudis Duran
Eudis Duran

Reputation: 782

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

Upvotes: 1

Related Questions