@dotenvx/dotenvx 2.31.1 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/README.md +100 -28
  3. package/package.json +3 -3
  4. package/src/cli/actions/check.js +45 -38
  5. package/src/cli/actions/init.js +23 -13
  6. package/src/cli/actions/protectStdin.js +19 -3
  7. package/src/cli/actions/run.js +15 -11
  8. package/src/cli/commands/primitives.js +1 -1
  9. package/src/cli/dotenvx.js +8 -7
  10. package/src/lib/{envfile → envspec}/discovery/discoverEnvFiles.js +1 -1
  11. package/src/lib/{envfile → envspec}/discovery/scanSource.js +1 -1
  12. package/src/lib/{envfile/parsing/envfile.peggy → envspec/parsing/envspec.peggy} +17 -10
  13. package/src/lib/{envfile/parsing/envfileParser.js → envspec/parsing/envspecParser.js} +575 -455
  14. package/src/lib/{envfile/parsing/formatEnvfileSyntaxError.js → envspec/parsing/formatEnvspecSyntaxError.js} +1 -1
  15. package/src/lib/{envfile/parsing/readEnvfile.js → envspec/parsing/readEnvspec.js} +38 -27
  16. package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js} +7 -10
  17. package/src/lib/envspec/rendering/previewEnvspec.js +51 -0
  18. package/src/lib/envspec/rendering/renderEnvspec.js +30 -0
  19. package/src/lib/envspec/validation/diagnosticLocation.js +29 -0
  20. package/src/lib/envspec/validation/protectEnvspec.js +39 -0
  21. package/src/lib/envspec/validation/validateEnvspec.js +57 -0
  22. package/src/lib/helpers/errors.js +7 -6
  23. package/src/lib/helpers/isPublicKey.js +3 -0
  24. package/src/lib/helpers/plaintextKeys.js +9 -0
  25. package/src/lib/helpers/redactedValues.js +10 -4
  26. package/src/lib/services/init.js +27 -22
  27. package/src/lib/services/validate.js +20 -10
  28. package/src/lib/transforms/encrypt.js +21 -8
  29. package/src/lib/envfile/rendering/renderEnvfile.js +0 -26
  30. package/src/lib/envfile/validation/validateEnvfile.js +0 -24
  31. /package/src/lib/{envfile → envspec}/discovery/extractEnvKeys.js +0 -0
  32. /package/src/lib/{envfile → envspec}/validation/encryptedSources.js +0 -0
  33. /package/src/lib/{envfile → envspec}/validation/validate.js +0 -0
@@ -2,23 +2,31 @@ const envsResolver = require('../resolvers/envs')
2
2
  const Session = require('../../db/session')
3
3
  const buildCommandEnvs = require('../helpers/buildCommandEnvs')
4
4
  const resolveEnvKeysFile = require('../helpers/resolveEnvKeysFile')
5
- const readEnvfile = require('../envfile/parsing/readEnvfile')
6
- const validateEnvfile = require('../envfile/validation/validateEnvfile')
5
+ const readEnvspec = require('../envspec/parsing/readEnvspec')
6
+ const validateEnvspec = require('../envspec/validation/validateEnvspec')
7
7
  const normalizeDotenvConfigPath = require('../helpers/normalizeDotenvConfigPath')
8
8
  const Errors = require('../helpers/errors')
9
9
  const { determine } = require('../helpers/envResolution')
10
+ const path = require('node:path')
11
+ const resolveDirectoryFilepath = require('../helpers/resolveDirectoryFilepath')
10
12
 
11
13
  // Load once and validate the final values; callers own presentation and execution.
12
- module.exports = async function validate ({ envs = [], options = {}, processEnv = { ...process.env }, requireEnvfile = true, command, onStatus } = {}) {
13
- envs = buildCommandEnvs(normalizeDotenvConfigPath(envs, processEnv), options.convention)
14
+ module.exports = async function validate ({ envs = [], options = {}, processEnv = { ...process.env }, requireEnvspec = true, command, onStatus, onKey } = {}) {
15
+ envs = normalizeDotenvConfigPath(envs, processEnv)
16
+ const requiredFilepaths = new Set(envs.filter(env => env.type === 'envFile').flatMap(env => {
17
+ const resolved = resolveDirectoryFilepath(env.value, '.env')
18
+ // A directory with a convention selects optional layers rather than one file.
19
+ return options.convention && resolved !== env.value ? [] : [path.resolve(resolved)]
20
+ }))
21
+ envs = buildCommandEnvs(envs, options.convention)
14
22
  envs = determine(envs, processEnv)
15
- const schema = readEnvfile(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
16
- if (requireEnvfile && !schema.exists) throw new Errors().envfileRequired()
23
+ const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
24
+ if (requireEnvspec && !schema.exists) throw new Errors().envspecRequired()
17
25
 
18
26
  const session = new Session()
19
27
  const proxyToken = options.token || processEnv.DOTENVX_TOKEN
20
28
  const noArmor = options.armor === false || (!proxyToken && (await session.noArmor()))
21
- if (schema.proxyRules.size > 0 && noArmor) throw new Error('Envfile proxy requires Armor. Enable Armor and authenticate before running.')
29
+ if (schema.proxyRules.size > 0 && noArmor) throw new Error('Envspec proxy requires Armor. Enable Armor and authenticate before running.')
22
30
  const proxyCredentials = noArmor ? undefined : []
23
31
  const { processedEnvs, readableFilepaths } = await envsResolver({
24
32
  envs,
@@ -40,7 +48,7 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
40
48
  let proxyError
41
49
  for (const name of schema.proxyRules.keys()) {
42
50
  if (processEnv[name] !== undefined && !(proxyCredentials || []).some(credential => credential.name === name && credential.placeholder === processEnv[name])) {
43
- proxyError = new Error(`Envfile proxy requires an encrypted ${name} loaded from an env file. Remove plaintext or shell overrides, or use --overload.`)
51
+ proxyError = new Error(`Envspec proxy requires an encrypted ${name} loaded from an env file. Remove plaintext or shell overrides, or use --overload.`)
44
52
  break
45
53
  }
46
54
  }
@@ -49,11 +57,13 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
49
57
  processEnv,
50
58
  processedEnvs,
51
59
  readableFilepaths,
52
- hasEnvfile: schema.exists,
60
+ requiredFilepaths,
61
+ hasEnvspec: schema.exists,
62
+ schema,
53
63
  proxyCredentials,
54
64
  proxyToken,
55
65
  session,
56
66
  proxyError,
57
- validationError: validateEnvfile(schema, processEnv, processedEnvs)
67
+ validationError: validateEnvspec(schema, processEnv, processedEnvs, onKey)
58
68
  }
59
69
  }
@@ -1,5 +1,6 @@
1
1
  const fsx = require('./../helpers/fsx')
2
2
  const path = require('path')
3
+ const fs = require('node:fs')
3
4
  const { encrypted, encrypt, scan, upsert, publickeys, keypair } = require('@dotenvx/primitives')
4
5
 
5
6
  const TYPE_ENV_FILE = 'envFile'
@@ -13,6 +14,7 @@ const keynames = require('../conventions/keynames')
13
14
 
14
15
  const selectKeyStorage = require('../helpers/selectKeyStorage')
15
16
  const custodians = require('../custodians')
17
+ const readEnvspec = require('../envspec/parsing/readEnvspec')
16
18
 
17
19
  async function encryptTransform (options = {}) {
18
20
  const envs = options.envs || []
@@ -52,6 +54,11 @@ async function encryptTransform (options = {}) {
52
54
  const row = { keys: [], type: TYPE_ENV_FILE, filepath, envFilepath, changed: false }
53
55
 
54
56
  try {
57
+ const policyPath = path.resolve('Envspec')
58
+ const schema = readEnvspec(policyPath, [filepath])
59
+ if (!schema.exists && fs.lstatSync(policyPath, { throwIfNoEntry: false })) {
60
+ throw new Error(`Cannot read Envspec: ${policyPath}`)
61
+ }
55
62
  const fileExists = await fsx.exists(filepath)
56
63
  if (!fileExists && !noCreate) {
57
64
  row.envSrc = SAMPLE_ENV_KIT
@@ -61,11 +68,23 @@ async function encryptTransform (options = {}) {
61
68
  row.envSrc = await fsx.readFileX(filepath, { encoding })
62
69
  }
63
70
 
64
- if (row.envSrc.trim().length === 0) {
71
+ if (!schema.exists && row.envSrc.trim().length === 0) {
65
72
  row.envSrc = SAMPLE_ENV_KIT
66
73
  row.changed = true
67
74
  }
68
75
 
76
+ const { parsed } = scan(row.envSrc, { ik, ek })
77
+ const selected = Object.entries(parsed).filter(([key]) => {
78
+ if (isDotenvPublicKey(key)) return false
79
+ return schema.exists ? (schema.encryptionRules.get(key) ?? schema.encrypted) : !isPlainKey(key)
80
+ })
81
+ if (schema.exists && !selected.some(([, values]) => values.some(value => !encrypted(value)))) {
82
+ row.changed = false
83
+ unchangedFilepaths.push(envFilepath)
84
+ processedEnvs.push(row)
85
+ continue
86
+ }
87
+
69
88
  let publicKey = publickeys(row.envSrc)[0]
70
89
 
71
90
  if (!publicKey) {
@@ -86,13 +105,7 @@ async function encryptTransform (options = {}) {
86
105
  if (stored.nativePrivateKeyAdded) row.nativePrivateKeyAdded = true
87
106
  }
88
107
 
89
- const { parsed } = scan(row.envSrc, { ik, ek })
90
-
91
- for (const [key, values] of Object.entries(parsed)) {
92
- if (isDotenvPublicKey(key) || isPlainKey(key)) {
93
- continue
94
- }
95
-
108
+ for (const [key, values] of selected) {
96
109
  const transformedValues = []
97
110
  for (const value of values) {
98
111
  if (encrypted(value)) {
@@ -1,26 +0,0 @@
1
- function declaration (item) {
2
- let line = `env "${item.name}"`
3
- if (item.type) line += `, type: "${item.type}"`
4
- if (item.encrypted !== undefined) line += `, encrypted: ${item.encrypted}`
5
- if (item.optional !== undefined) line += `, optional: ${item.optional}`
6
- return line
7
- }
8
-
9
- module.exports = function renderEnvfile (document) {
10
- const sections = [`encrypted ${document.encrypted}`]
11
- if (document.declarations.length) sections.push(document.declarations.map(declaration).join('\n'))
12
- for (const file of document.files) {
13
- const quote = file.filename.includes('"') ? "'" : '"'
14
- if (file.filename.includes(quote) || /[\r\n\0*?[\]{}]/.test(file.filename)) {
15
- throw new Error(`Unsupported Envfile filename: ${file.filename}`)
16
- }
17
- const lines = [`file ${quote}${file.filename}${quote} do`]
18
- if (file.encrypted !== undefined) lines.push(` encrypted ${file.encrypted}`)
19
- lines.push(...file.declarations.map(item => ` ${declaration(item)}`), 'end')
20
- sections.push(lines.join('\n'))
21
- }
22
- if (document.codeDeclarations.length) {
23
- sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
24
- }
25
- return sections.join('\n\n') + '\n'
26
- }
@@ -1,24 +0,0 @@
1
- const validate = require('./validate')
2
- const encryptedSources = require('./encryptedSources')
3
- const Errors = require('../../helpers/errors')
4
-
5
- module.exports = function validateEnvfile (schema, env, processedEnvs) {
6
- const messages = new Set()
7
- const schemas = schema.schemas || [schema]
8
- const sources = schemas.some(rules => rules.encryptedKeys.length > 0) ? encryptedSources(processedEnvs) : undefined
9
- for (const rules of schemas) {
10
- const { requiredKeys, types, enums, ranges, encryptedKeys } = rules
11
- const required = Object.fromEntries(requiredKeys.map(key => [key, '']))
12
- const validation = validate(required, env, {
13
- types,
14
- enums,
15
- ranges,
16
- encryptedKeys,
17
- encryptedSources: sources
18
- })
19
- for (const error of validation.errors) messages.add(error.message)
20
- }
21
- if (messages.size > 0) {
22
- return new Errors({ message: [...messages].join('; ') }).invalidEnv()
23
- }
24
- }