Skip to content

Commit

Permalink
create package
Browse files Browse the repository at this point in the history
  • Loading branch information
kjellrichard committed Sep 6, 2017
1 parent af202f6 commit 694bcfc
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ typings/
# dotenv environment variables file
.env

.idea
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,30 @@
# njs-tfso-secret
Reads secret from files in a directory
Get secret values from file

Try to read file and returns content as value.
Name of file is name of key, file location is determined by config.

Note: Reading is sync. Use only on startup.

## install
`npm install tfso/njs-tfso-secret`

## usage
```javascript
const secret = require('njs-tfso-secret');

let value = secret.get('some-secret', 'somedefaultvalue');


//custom config
secret.config({
location: '/run/secrets', // default
silent: false // if false, log to console if error reading keys from file. Default is "true"
});


// use together with getenv
const env = require('getenv');

let valueWithDefaultFromEnv = secrets.get('PASSWORD',env.string('PASSWORD', ''))
```
42 changes: 42 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const fs = require('fs');
const path = require('path');

class Secret {
constructor(config) {
this._secrets = {};
this.config(config);
}

config(config) {
this._config = Object.assign(this._config || {},config);
}

read(key) {
let fullPath = path.join(this._config.location,key),
value = null;
try {
this._secrets[key] = value = fs.readFileSync(fullPath,'utf8');
} catch(ex) {
if ( !this._config.silent )
console.log(`secret: unable to read key ${key} from file ${fullPath}`);
}
return value;
}

get(key, defaultValue=null) {
let value;
if ( !!(value = this._secrets[key]))
return value;
value = this.read(key);
return !!value ? value : defaultValue;
}
}


module.exports = (config=>{
let secret = new Secret(config);
return {
config: secret.config.bind(secret),
get: secret.get.bind(secret)
};
})({location:'/run/secrets', silent: true});
23 changes: 23 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "njs-tfso-secret",
"version": "1.0.0",
"description": "Get secret values by reading from file",
"main": "index.js",
"scripts": {

},
"repository": {
"type": "git",
"url": "git+https://github.com/tfso/njs-tfso-secret.git"
},
"keywords": [
"tfso",
"secret"
],
"author": "Richard B",
"license": "UNLICENSED",
"bugs": {
"url": "https://github.com/tfso/njs-tfso-secret/issues"
},
"homepage": "https://github.com/tfso/njs-tfso-secret#readme"
}

0 comments on commit 694bcfc

Please # to comment.