main.js 10 KB

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