1 | const fs = require('fs')
|
2 | const path = require('path')
|
3 | const os = require('os')
|
4 | const crypto = require('crypto')
|
5 | const packageJson = require('../package.json')
|
6 |
|
7 | const version = packageJson.version
|
8 |
|
9 | const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg
|
10 |
|
11 |
|
12 | function parse (src) {
|
13 | const obj = {}
|
14 |
|
15 |
|
16 | let lines = src.toString()
|
17 |
|
18 |
|
19 | lines = lines.replace(/\r\n?/mg, '\n')
|
20 |
|
21 | let match
|
22 | while ((match = LINE.exec(lines)) != null) {
|
23 | const key = match[1]
|
24 |
|
25 |
|
26 | let value = (match[2] || '')
|
27 |
|
28 |
|
29 | value = value.trim()
|
30 |
|
31 |
|
32 | const maybeQuote = value[0]
|
33 |
|
34 |
|
35 | value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')
|
36 |
|
37 |
|
38 | if (maybeQuote === '"') {
|
39 | value = value.replace(/\\n/g, '\n')
|
40 | value = value.replace(/\\r/g, '\r')
|
41 | }
|
42 |
|
43 |
|
44 | obj[key] = value
|
45 | }
|
46 |
|
47 | return obj
|
48 | }
|
49 |
|
50 | function _parseVault (options) {
|
51 | const vaultPath = _vaultPath(options)
|
52 |
|
53 |
|
54 | const result = DotenvModule.configDotenv({ path: vaultPath })
|
55 | if (!result.parsed) {
|
56 | throw new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
|
57 | }
|
58 |
|
59 |
|
60 |
|
61 | const keys = _dotenvKey(options).split(',')
|
62 | const length = keys.length
|
63 |
|
64 | let decrypted
|
65 | for (let i = 0; i < length; i++) {
|
66 | try {
|
67 |
|
68 | const key = keys[i].trim()
|
69 |
|
70 |
|
71 | const attrs = _instructions(result, key)
|
72 |
|
73 |
|
74 | decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)
|
75 |
|
76 | break
|
77 | } catch (error) {
|
78 |
|
79 | if (i + 1 >= length) {
|
80 | throw error
|
81 | }
|
82 |
|
83 | }
|
84 | }
|
85 |
|
86 |
|
87 | return DotenvModule.parse(decrypted)
|
88 | }
|
89 |
|
90 | function _log (message) {
|
91 | console.log(`[dotenv@${version}][INFO] ${message}`)
|
92 | }
|
93 |
|
94 | function _warn (message) {
|
95 | console.log(`[dotenv@${version}][WARN] ${message}`)
|
96 | }
|
97 |
|
98 | function _debug (message) {
|
99 | console.log(`[dotenv@${version}][DEBUG] ${message}`)
|
100 | }
|
101 |
|
102 | function _dotenvKey (options) {
|
103 |
|
104 | if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
|
105 | return options.DOTENV_KEY
|
106 | }
|
107 |
|
108 |
|
109 | if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
|
110 | return process.env.DOTENV_KEY
|
111 | }
|
112 |
|
113 |
|
114 | return ''
|
115 | }
|
116 |
|
117 | function _instructions (result, dotenvKey) {
|
118 |
|
119 | let uri
|
120 | try {
|
121 | uri = new URL(dotenvKey)
|
122 | } catch (error) {
|
123 | if (error.code === 'ERR_INVALID_URL') {
|
124 | throw new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development')
|
125 | }
|
126 |
|
127 | throw error
|
128 | }
|
129 |
|
130 |
|
131 | const key = uri.password
|
132 | if (!key) {
|
133 | throw new Error('INVALID_DOTENV_KEY: Missing key part')
|
134 | }
|
135 |
|
136 |
|
137 | const environment = uri.searchParams.get('environment')
|
138 | if (!environment) {
|
139 | throw new Error('INVALID_DOTENV_KEY: Missing environment part')
|
140 | }
|
141 |
|
142 |
|
143 | const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`
|
144 | const ciphertext = result.parsed[environmentKey]
|
145 | if (!ciphertext) {
|
146 | throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
|
147 | }
|
148 |
|
149 | return { ciphertext, key }
|
150 | }
|
151 |
|
152 | function _vaultPath (options) {
|
153 | let dotenvPath = path.resolve(process.cwd(), '.env')
|
154 |
|
155 | if (options && options.path && options.path.length > 0) {
|
156 | dotenvPath = options.path
|
157 | }
|
158 |
|
159 |
|
160 | return dotenvPath.endsWith('.vault') ? dotenvPath : `${dotenvPath}.vault`
|
161 | }
|
162 |
|
163 | function _resolveHome (envPath) {
|
164 | return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
|
165 | }
|
166 |
|
167 | function _configVault (options) {
|
168 | _log('Loading env from encrypted .env.vault')
|
169 |
|
170 | const parsed = DotenvModule._parseVault(options)
|
171 |
|
172 | let processEnv = process.env
|
173 | if (options && options.processEnv != null) {
|
174 | processEnv = options.processEnv
|
175 | }
|
176 |
|
177 | DotenvModule.populate(processEnv, parsed, options)
|
178 |
|
179 | return { parsed }
|
180 | }
|
181 |
|
182 | function configDotenv (options) {
|
183 | let dotenvPath = path.resolve(process.cwd(), '.env')
|
184 | let encoding = 'utf8'
|
185 | const debug = Boolean(options && options.debug)
|
186 |
|
187 | if (options) {
|
188 | if (options.path != null) {
|
189 | dotenvPath = _resolveHome(options.path)
|
190 | }
|
191 | if (options.encoding != null) {
|
192 | encoding = options.encoding
|
193 | } else {
|
194 | if (debug) {
|
195 | _debug('No encoding is specified. UTF-8 is used by default')
|
196 | }
|
197 | }
|
198 | }
|
199 |
|
200 | try {
|
201 |
|
202 | const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding }))
|
203 |
|
204 | let processEnv = process.env
|
205 | if (options && options.processEnv != null) {
|
206 | processEnv = options.processEnv
|
207 | }
|
208 |
|
209 | DotenvModule.populate(processEnv, parsed, options)
|
210 |
|
211 | return { parsed }
|
212 | } catch (e) {
|
213 | if (debug) {
|
214 | _debug(`Failed to load ${dotenvPath} ${e.message}`)
|
215 | }
|
216 |
|
217 | return { error: e }
|
218 | }
|
219 | }
|
220 |
|
221 |
|
222 | function config (options) {
|
223 | const vaultPath = _vaultPath(options)
|
224 |
|
225 |
|
226 | if (_dotenvKey(options).length === 0) {
|
227 | return DotenvModule.configDotenv(options)
|
228 | }
|
229 |
|
230 |
|
231 | if (!fs.existsSync(vaultPath)) {
|
232 | _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)
|
233 |
|
234 | return DotenvModule.configDotenv(options)
|
235 | }
|
236 |
|
237 | return DotenvModule._configVault(options)
|
238 | }
|
239 |
|
240 | function decrypt (encrypted, keyStr) {
|
241 | const key = Buffer.from(keyStr.slice(-64), 'hex')
|
242 | let ciphertext = Buffer.from(encrypted, 'base64')
|
243 |
|
244 | const nonce = ciphertext.subarray(0, 12)
|
245 | const authTag = ciphertext.subarray(-16)
|
246 | ciphertext = ciphertext.subarray(12, -16)
|
247 |
|
248 | try {
|
249 | const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)
|
250 | aesgcm.setAuthTag(authTag)
|
251 | return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
|
252 | } catch (error) {
|
253 | const isRange = error instanceof RangeError
|
254 | const invalidKeyLength = error.message === 'Invalid key length'
|
255 | const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'
|
256 |
|
257 | if (isRange || invalidKeyLength) {
|
258 | const msg = 'INVALID_DOTENV_KEY: It must be 64 characters long (or more)'
|
259 | throw new Error(msg)
|
260 | } else if (decryptionFailed) {
|
261 | const msg = 'DECRYPTION_FAILED: Please check your DOTENV_KEY'
|
262 | throw new Error(msg)
|
263 | } else {
|
264 | console.error('Error: ', error.code)
|
265 | console.error('Error: ', error.message)
|
266 | throw error
|
267 | }
|
268 | }
|
269 | }
|
270 |
|
271 |
|
272 | function populate (processEnv, parsed, options = {}) {
|
273 | const debug = Boolean(options && options.debug)
|
274 | const override = Boolean(options && options.override)
|
275 |
|
276 | if (typeof parsed !== 'object') {
|
277 | throw new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
|
278 | }
|
279 |
|
280 |
|
281 | for (const key of Object.keys(parsed)) {
|
282 | if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
|
283 | if (override === true) {
|
284 | processEnv[key] = parsed[key]
|
285 | }
|
286 |
|
287 | if (debug) {
|
288 | if (override === true) {
|
289 | _debug(`"${key}" is already defined and WAS overwritten`)
|
290 | } else {
|
291 | _debug(`"${key}" is already defined and was NOT overwritten`)
|
292 | }
|
293 | }
|
294 | } else {
|
295 | processEnv[key] = parsed[key]
|
296 | }
|
297 | }
|
298 | }
|
299 |
|
300 | const DotenvModule = {
|
301 | configDotenv,
|
302 | _configVault,
|
303 | _parseVault,
|
304 | config,
|
305 | decrypt,
|
306 | parse,
|
307 | populate
|
308 | }
|
309 |
|
310 | module.exports.configDotenv = DotenvModule.configDotenv
|
311 | module.exports._configVault = DotenvModule._configVault
|
312 | module.exports._parseVault = DotenvModule._parseVault
|
313 | module.exports.config = DotenvModule.config
|
314 | module.exports.decrypt = DotenvModule.decrypt
|
315 | module.exports.parse = DotenvModule.parse
|
316 | module.exports.populate = DotenvModule.populate
|
317 |
|
318 | module.exports = DotenvModule
|