Skip to content

Commit

Permalink
Merge pull request #8 from kunalpanchal/refactor/standard-fix
Browse files Browse the repository at this point in the history
  • Loading branch information
kunalpanchal committed Oct 8, 2019
2 parents 4aec4f9 + 61bda80 commit 94c2bd4
Show file tree
Hide file tree
Showing 8 changed files with 461 additions and 435 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -56,3 +56,6 @@ typings/

# dotenv environment variables file
.env

# Build directories
dist
18 changes: 9 additions & 9 deletions lib/cli.js
@@ -1,17 +1,17 @@
#! /usr/bin/env node

/* Arguments that can be passed are
/* Arguments that can be passed are
* --secret <secretKey> | -s <secretKey>
* --out <file-path> | -o <file-path>
* --algo <algoName> | -a <algoName>
* --algo <algoName> | -a <algoName>
*/

const argv = require('minimist')(process.argv.slice(2));
const outputFile = argv.outputFile || argv.o;
const inputFile = argv._[0];
const secret = argv.secret || argv.s;
const encryptionAlgo = argv.algo || argv.a;
const argv = require('minimist')(process.argv.slice(2))
const outputFile = argv.outputFile || argv.o
const inputFile = argv._[0]
const secret = argv.secret || argv.s
const encryptionAlgo = argv.algo || argv.a

const cryptography = require('./cryptography');
const cryptography = require('./cryptography')

cryptography.encrypt({ secret, inputFile, outputFile, encryptionAlgo });
cryptography.encrypt({ secret, inputFile, outputFile, encryptionAlgo })
87 changes: 43 additions & 44 deletions lib/cryptography.js
@@ -1,53 +1,52 @@
"use strict"
'use strict'

const crypto = require('crypto');
const fs = require('fs');
const log = require('./utils/log');
const crypto = require('crypto')
const fs = require('fs')
const log = require('./utils/log')

/* Arguments that can be passed are
/* Arguments that can be passed are
* --secret <secretKey> | -s <secretKey>
* --out <file-path> | -o <file-path>
* --algo <algoName> | -a <algoName>
* --algo <algoName> | -a <algoName>
*/

module.exports.decrypt = (options) => {
try {
const secret = options.secret || 'mySecret';
const inputFile = options.file || '.env.enc';
const decryptionAlgo = options.decryptionAlgo || `aes192`;

if (!fs.existsSync(inputFile)) throw `${inputFile} does not exist.`
if (!secret || typeof (secret) !== 'string') throw 'No SecretKey provided.';

const decipher = crypto.createDecipher(decryptionAlgo, secret);
let decrypted = decipher.update(fs.readFileSync(inputFile), 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (e) {
log(e, 'error');
}
};
try {
const secret = options.secret || 'mySecret'
const inputFile = options.file || '.env.enc'
const decryptionAlgo = options.decryptionAlgo || 'aes192'

if (!fs.existsSync(inputFile)) throw `${inputFile} does not exist.`
if (!secret || typeof (secret) !== 'string') throw 'No SecretKey provided.'

const decipher = crypto.createDecipher(decryptionAlgo, secret)
let decrypted = decipher.update(fs.readFileSync(inputFile), 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
} catch (e) {
log(e, 'error')
}
}

module.exports.encrypt = (options) => {
try {
const secret = options.secret || 'mySecret';
const inputFile = options.inputFile || '.env';
const outputFilePath = options.outputFile || `${inputFile}.enc`;
const encryptionAlgo = options.encryptionAlgo || `aes192`;

if (!fs.existsSync(inputFile)) throw `Error: ${inputFile} does not exist.`
if (!secret || typeof (secret) !== 'string') throw 'No SecretKey provided.Use -s option to specify secret';

const cipher = crypto.createCipher(encryptionAlgo, secret);
const output = fs.createWriteStream(outputFilePath);
fs.createReadStream(inputFile).pipe(cipher).pipe(output);

output.on('finish', () => {
log(`The Environment file "${inputFile}" has been encrypted to "${outputFilePath}".`, 'info');
log(`Make sure to delete "${inputFile}" for production use.`, 'warn');
});

} catch (e) {
log(e, 'error');
}
};
try {
const secret = options.secret || 'mySecret'
const inputFile = options.inputFile || '.env'
const outputFilePath = options.outputFile || `${inputFile}.enc`
const encryptionAlgo = options.encryptionAlgo || 'aes192'

if (!fs.existsSync(inputFile)) throw `Error: ${inputFile} does not exist.`
if (!secret || typeof (secret) !== 'string') throw 'No SecretKey provided.Use -s option to specify secret'

const cipher = crypto.createCipher(encryptionAlgo, secret)
const output = fs.createWriteStream(outputFilePath)
fs.createReadStream(inputFile).pipe(cipher).pipe(output)

output.on('finish', () => {
log(`The Environment file "${inputFile}" has been encrypted to "${outputFilePath}".`, 'info')
log(`Make sure to delete "${inputFile}" for production use.`, 'warn')
})
} catch (e) {
log(e, 'error')
}
}
42 changes: 20 additions & 22 deletions lib/index.js
@@ -1,9 +1,8 @@
'use strict'

const fs = require('fs');
const cryptography = require('./cryptography');
const log = require('./utils/log');
const parser = require('./parser');
const cryptography = require('./cryptography')
const log = require('./utils/log')
const parser = require('./parser')

/*
* Options Expected
Expand All @@ -13,22 +12,21 @@ const parser = require('./parser');
*/

module.exports = (options) => {
try {
let decryptedContent = cryptography.decrypt({
secret: options.secret,
file: options.path,
decryptionAlgo: options.enc_algo
});
if (decryptedContent) {
let env = {};
let parsedObj = parser(decryptedContent);
Object.keys(parsedObj).forEach(key => {
if (!env.hasOwnProperty(key))
env[key] = parsedObj[key]
})
return env;
}
} catch (e) {
log(e, 'error');
try {
const decryptedContent = cryptography.decrypt({
secret: options.secret,
file: options.path,
decryptionAlgo: options.enc_algo
})
if (decryptedContent) {
const env = {}
const parsedObj = parser(decryptedContent)
Object.keys(parsedObj).forEach(key => {
if (!env.hasOwnProperty(key)) { env[key] = parsedObj[key] }
})
return env
}
}
} catch (e) {
log(e, 'error')
}
}
44 changes: 22 additions & 22 deletions lib/parser.js
Expand Up @@ -3,25 +3,25 @@
*/

module.exports = (src) => {
let obj = {}
// convert Buffers before splitting into lines and processing
src.toString().split('\n').forEach(function (line) {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1]
// default undefined or missing values to empty string
let value = keyValueArr[2] || ''
// expand newlines in quoted values
let len = value ? value.length : 0
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n')
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim()
obj[key] = value
}
})
return obj;
}
const obj = {}
// convert Buffers before splitting into lines and processing
src.toString().split('\n').forEach(function (line) {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1]
// default undefined or missing values to empty string
let value = keyValueArr[2] || ''
// expand newlines in quoted values
const len = value ? value.length : 0
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n')
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim()
obj[key] = value
}
})
return obj
}
56 changes: 28 additions & 28 deletions lib/utils/log.js
@@ -1,35 +1,35 @@
const colorCodes = {
BLACK: "\x1b[30m",
RED: "\x1b[31m",
GREEN: "\x1b[32m",
YELLOW: "\x1b[33m",
BLUE: "\x1b[34m",
MAGENTA: "\x1b[35m",
CYAN: "\x1b[36m",
RESET: "\x1b[0m"
BLACK: '\x1b[30m',
RED: '\x1b[31m',
GREEN: '\x1b[32m',
YELLOW: '\x1b[33m',
BLUE: '\x1b[34m',
MAGENTA: '\x1b[35m',
CYAN: '\x1b[36m',
RESET: '\x1b[0m'
}

function getColorCode(colorName) {
let colorCode = colorCodes[colorName.toUpperCase()];
return colorCode || colorCodes.RESET;
function getColorCode (colorName) {
const colorCode = colorCodes[colorName.toUpperCase()]
return colorCode || colorCodes.RESET
}

module.exports = (data, type, color) => {
if (data) {
let logData = `${colorCodes.CYAN}Secure-env : ${colorCodes.RESET}`;
switch (type.toUpperCase()) {
case `ERROR`:
logData += `${colorCodes.RED} ERROR OCCURED ${colorCodes.RESET}`
break;
case `INFO`:
logData += `${colorCodes.GREEN} INFO ${colorCodes.RESET}`
break;
case `WARN`:
logData += `${colorCodes.YELLOW} WARNING ${colorCodes.RESET}`
break;
}

logData += color ? `${getColorCode(color)}${data}${colorCodes.RESET}` : data;
console.log(logData);
if (data) {
let logData = `${colorCodes.CYAN}Secure-env : ${colorCodes.RESET}`
switch (type.toUpperCase()) {
case 'ERROR':
logData += `${colorCodes.RED} ERROR OCCURED ${colorCodes.RESET}`
break
case 'INFO':
logData += `${colorCodes.GREEN} INFO ${colorCodes.RESET}`
break
case 'WARN':
logData += `${colorCodes.YELLOW} WARNING ${colorCodes.RESET}`
break
}
}

logData += color ? `${getColorCode(color)}${data}${colorCodes.RESET}` : data
console.log(logData)
}
}

0 comments on commit 94c2bd4

Please sign in to comment.