Giter Club home page Giter Club logo

envy's Introduction

envy

Load .env files and environment variables

Build status for Envy

Secure and friendly alternative to dotenv, using functional programming, with strong tests to prove its safety.

Follows the Twelve Factor App methodology.

Contents

Why?

  • Safest environment loader around.
  • Validates file permissions are secure.
  • Validates required env vars are defined.
  • No side effects, does not modify process.env.
  • Returns property names in camelCase.
  • Asserts that .env is ignored in git.

You want to keep your secrets safe, right? envy loads your app's configuration values from a .env file and prevents mistakes, such as accidentally committing the .env file to your repository, or leaving .env with unsafe permissions.

Have you spent a day rotating passwords because a developer accidentally pushed them to the repository? Yeah, that actually happens and it can cause chaos at companies. It doesn't matter if you delete the commit. Once it's out there, game over. People who are authorized to read the repository may not be authorized to have those credentials, including third party tools and services. If the repository is public, search engines may have crawled it. Consider everything to be compromised.

The envy module helps you prevent that situation by providing a convenient mechanism for everyone to store credentials and other config locally and validate that it is correct without commiting them to the repository. It verifies that all relevant files have secure permissions and that the secrets file is explicitly ignored so that it cannot accidentally be commited.

Install

npm install envy --save

Usage

const envy = require('envy');
const env = envy();
console.log(env);
// {
//     foo : 'bar'
// }

A .env.example file is used as a template to determine which environment variables are required by your application. This file should be commited to your repository.

# .env.example
FOO=

A .env file is used to provide the actual environment values. You must add this file to a local .gitignore to prevent leaking secrets and envy will check that you did this correctly.

# .env
FOO=bar

Environment files look just like normal shell files (e.g. .bashrc and friends). Values may be optionally wrapped in ' single quotes. This is recommended for shell compatibility, in case the value contains whitespace.

# This is a comment.
FOO=bar
SENTENCE='Hi, there!'

After assembling the environment from .env and process.env, it is filtered by a union of the properties in .env and .env.example. In other words, variables defined in either file will be returned and variables not defined in either file will be ignored. This is done to prevent surprising behavior, since process.env often contains a wide variety of variables, some of which are implicitly set without the user's direct knowledge. It is better to be explicit about the variables you use, which improves safety and debugging.

API

envy(filepath)

Returns an object with environment variables derived from process.env and the contents at filepath. If a variable is defined in both places, process.env takes precedence so that users can easily override values on the command line. If all required variables are present in process.env, then the .env file need not exist. All property names are returned in camelcase.

filepath

Type: string
Default: .env

Path to the file where environment variables are kept. Must be hidden (start with a .). Will also be used to compute the path of the example file (by appending .example).

Tips

Mixing with command line options

Make a CLI with meow and use joi to further validate and parse the returned values.

// cli.js
const meow = require('meow');
const envy = require('envy');
const joi = require('joi');

const cli = meow();

const input = Object.assign({}, envy(), cli.flags);
const config = joi.attempt(input, {
    port : joi.number().positive().integer().min(0).max(65535)
});
// value.port has been parsed as a number
console.log('port:', config.port);
# .env.example
PORT=
# .env
PORT=1000
$ node cli.js
port: 1000
$ PORT=2000 node cli.js
port: 2000
$ node cli.js --port=3000
port: 3000
$ PORT=2000 node cli.js --port=3000
port: 3000

Modifying process.env

We recommend not using process.env directly. But let's say you want to because a dependency expects you to set NODE_ENV and you want to define it in .env. No problem!

You should first ask the project to accept options as input so you don't need this.

const envy = require('envy');
const decamelize = require('decamelize');

const override = Object.entries(envy()).reduce((result, [key, val]) => {
    result[decamelize(key).toUpperCase()] = val;
    return result;
}, {});
Object.assign(process.env, override);

FAQ

Why not dotenv or dotenv-safe?

I see this as a successor to those projects. But envy would not exist without them. dotenv brought .env files mainstream in Node.js projects. dotenv-safe improved on it by introducing the .env.example file. Now, envy takes this even further by securing your files and returning an object with camelcase keys rather than modifying process.env.

Resources

Related

  • meow - Make command line apps

Contributing

See our contributing guidelines for more details.

  1. Fork it.
  2. Make a feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request.

License

MPL-2.0 © Seth Holladay

Go make something, dang it.

envy's People

Contributors

devinivy avatar nargonath avatar sholladay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

envy's Issues

Add option for specifying the path to the .example file

I need to support multiple environments for my server. Also different environments have different variables. But there is not a clean/simple way to do it.
Right now to support 2 envs you will have to create .env.prod and .env.prod.example pairs for each env.

Ideally I would like to have max to files but maybe when you call:

    const env = envy({yourEnv});

and inside .env.example and .env you can have few functions???

Windows WSL .env file permissions problem

envy requires you to put 600 as file permission on .env. Alas if your workspace is in the Windows land you cannot change the file permission from your bash environment. The problem is that Windows' permissions system is not as granular as Linux' is. You cannot set a 600 on it (at least I haven't found a way) however you can set 666, 000 or 777.

One way to solve this is changing the permissions requirements based on the platform running envy, we could settle for 666 when process.platform === 'win32'.

Built-in shortcut for loading into process.env

The recipe for loading the environment variables into process.env is pretty simple, but it's nonetheless more cumbersome than it ought to be. We should include this feature as an optional part of our API.

My thought is something like:

envy.assign('.env', process.env);

Or, given that #5 will be implemented, perhaps:

envy.assign({ target : process.env });

Not sure about the names assign and target here. Suggestions for other names welcome.

File permissions check on Windows 10 platform fails

Even after performing chmod 555 .env envy throws file permission error on Windows 10 platform. This was attempted as administrator using both Cygwin and Gitbash CLIs.
In the Node v 10 REPL, fs.statSynch returns value of o444. Please refer to node documentation:
https://github.com/nodejs/node/blob/bf12414bbf4295cb47c4c8b69bc2aa6828778453/lib/fs.js#L1073
which mentions the following:
Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner or others is not implemented.

True cross-platform tests

Story

As a developer working on this library, I want CI to test my code on both *nix and Windows operating systems, so platform specific bugs and regressions are caught.

Implementation

Setup AppVeyor CI to run the tests in an actual Windows environment.

The setup-tests.sh script will need to be made cross-platform. One possible approach would be to re-write it in Node and use glob and fs.chmod().

Resources

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.