main.js 9.7 KB

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