-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (65 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const fs = require("fs")
const crypto = require("./crypto")
module.exports = {
/**
* encrypts a file with the given password
* @param {string} inPath - unencrypted file path
* @param {string} outPath - encrypted path to be written to
* @param {string} password
*/
encodeSync(inPath, outPath, password){
let text = fs.readFileSync(inPath)
let encrypted = crypto.encode(text, password)
fs.writeFileSync(outPath, encrypted, "utf-8")
},
/**
* reads an encoded file and returns string representation of file
* @param {string} path
* @param {string} password
* @returns {string}
*/
decodeSync(path, password){
let encrypted = fs.readFileSync(path, "utf-8")
let decrypted = crypto.decode(encrypted, password)
return decrypted
},
/**
* assigns key value pairs to the global `process.env` object
* @param json key value pairs to write
* @param allowOverwrite - if true, allows new keys to overwrite pre-existing keys already in `process.env`
*/
loadJSONToEnv(json, allowOverwrite = true){
const existingEnvironmentKeys = new Set(Object.keys(process.env))
for (const [key, value] of Object.entries(json)) {
if (existingEnvironmentKeys.has(key)){
if (allowOverwrite){
console.warn(`overwriting existing environment variable ${key} to ${value}`)
} else {
throw new Error(`cannot overwrite existing environment variable ${key} to ${value}`)
}
}
process.env[key] = value
}
},
/**
* reads an encrypted file from the filesystem with the given password
* @param {string} envFilePath
* @param {string} password
* @returns {json} json
*/
getJSON(envFilePath, password){
let decoded = this.decodeSync(envFilePath, password)
let json = JSON.parse(decoded)
return json
},
/**
* load an environment file directly to process.env
* @param {string} envFilePath
* @param {string} password
* @param {boolean} overWrite
*/
loadJSON(envFilePath, password, overWrite = true){
let json = this.getJSON(envFilePath, password)
this.loadJSONToEnv(json, overWrite)
}
}