@dotenvx/dotenvx 2.32.3 → 2.33.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 (61) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/README.md +43 -55
  3. package/package.json +3 -11
  4. package/src/cli/actions/check.js +7 -12
  5. package/src/cli/actions/encrypt.js +2 -2
  6. package/src/cli/actions/get.js +3 -3
  7. package/src/cli/actions/init.js +11 -11
  8. package/src/cli/actions/policy.js +14 -0
  9. package/src/cli/actions/primitivesCheck.js +32 -0
  10. package/src/cli/actions/primitivesProfile.js +15 -0
  11. package/src/cli/actions/primitivesRedact.js +19 -0
  12. package/src/cli/actions/protectStdin.js +2 -2
  13. package/src/cli/actions/run.js +6 -34
  14. package/src/cli/actions/set.js +1 -1
  15. package/src/cli/commands/primitives.js +28 -1
  16. package/src/cli/dotenvx.js +10 -5
  17. package/src/lib/custodians/local/onepassword.js +3 -5
  18. package/src/lib/{envspec → envfile}/discovery/discoverEnvFiles.js +1 -1
  19. package/src/lib/{envspec → envfile}/discovery/scanSource.js +1 -1
  20. package/src/lib/{envspec/parsing/formatEnvspecSyntaxError.js → envfile/parsing/formatEnvfileSyntaxError.js} +1 -1
  21. package/src/lib/envfile/parsing/readEnvfile.js +43 -0
  22. package/src/lib/envfile/parsing/resolveEnvfilePath.js +5 -0
  23. package/src/lib/{envspec/rendering/normalizeEnvspec.js → envfile/rendering/normalizeEnvfile.js} +1 -1
  24. package/src/lib/{envspec/rendering/previewEnvspec.js → envfile/rendering/previewEnvfile.js} +7 -15
  25. package/src/lib/{envspec/rendering/renderEnvspec.js → envfile/rendering/renderEnvfile.js} +4 -4
  26. package/src/lib/{envspec/validation/protectEnvspec.js → envfile/validation/protectEnvfile.js} +8 -10
  27. package/src/lib/envfile/validation/validateEnvfile.js +14 -0
  28. package/src/lib/helpers/errors.js +3 -12
  29. package/src/lib/helpers/executeCommand.js +1 -2
  30. package/src/lib/helpers/parseWithDecryptor.js +1 -9
  31. package/src/lib/helpers/redactOutput.js +30 -32
  32. package/src/lib/helpers/redactProcessOutput.js +58 -0
  33. package/src/lib/helpers/redactedValues.js +2 -2
  34. package/src/lib/helpers/selectEnvfileEnvs.js +29 -0
  35. package/src/lib/main.d.ts +14 -5
  36. package/src/lib/main.js +13 -19
  37. package/src/lib/resolvers/envs.js +5 -15
  38. package/src/lib/resolvers/get.js +2 -2
  39. package/src/lib/services/init.js +7 -7
  40. package/src/lib/services/validate.js +20 -31
  41. package/src/lib/transforms/encrypt.js +5 -5
  42. package/src/lib/transforms/set.js +5 -3
  43. package/src/lib/envspec/parsing/envspec.peggy +0 -105
  44. package/src/lib/envspec/parsing/envspecParser.js +0 -2851
  45. package/src/lib/envspec/parsing/readEnvspec.js +0 -151
  46. package/src/lib/envspec/parsing/resolveEnvspecPath.js +0 -12
  47. package/src/lib/envspec/validation/encryptedSources.js +0 -15
  48. package/src/lib/envspec/validation/validate.js +0 -109
  49. package/src/lib/envspec/validation/validateEnvspec.js +0 -57
  50. package/src/lib/helpers/isValidEmail.js +0 -11
  51. package/src/lib/helpers/isValidUrl.js +0 -9
  52. package/src/lib/proxy/configureProxy.js +0 -55
  53. package/src/lib/proxy/eligibleHeaders.js +0 -16
  54. package/src/lib/proxy/prepareProxy.js +0 -24
  55. package/src/lib/proxy/proxyCertificates.js +0 -44
  56. package/src/lib/proxy/proxyForward.js +0 -65
  57. package/src/lib/proxy/proxyPreload.js +0 -21
  58. package/src/lib/proxy/proxyPreloadSource.js +0 -3
  59. package/src/lib/proxy/proxyServer.js +0 -175
  60. /package/src/lib/{envspec → envfile}/discovery/extractEnvKeys.js +0 -0
  61. /package/src/lib/{envspec → envfile}/validation/diagnosticLocation.js +0 -0
@@ -0,0 +1,58 @@
1
+ const fs = require('node:fs')
2
+ const { createRedactor } = require('./redactOutput')
3
+
4
+ const stateKey = Symbol.for('dotenvx.redactProcessOutput')
5
+
6
+ // Keep a possible secret prefix between writes, including split UTF-8 buffers.
7
+ function install (stream, secrets) {
8
+ if (stream[stateKey]) {
9
+ stream[stateKey].add(secrets)
10
+ return
11
+ }
12
+ const redactor = createRedactor(secrets)
13
+ const write = stream.write.bind(stream)
14
+ const end = stream.end.bind(stream)
15
+ const consume = (chunk, encoding) => redactor.write(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk)
16
+ // Do not release an unfinished secret prefix at shutdown.
17
+ const flush = () => redactor.flush(true)
18
+
19
+ stream.write = function (chunk, encoding, callback) {
20
+ if (typeof encoding === 'function') {
21
+ callback = encoding
22
+ encoding = undefined
23
+ }
24
+ if (!(typeof chunk === 'string' || chunk instanceof Uint8Array) || (callback !== undefined && typeof callback !== 'function')) {
25
+ return write(chunk, encoding, callback)
26
+ }
27
+ return write(consume(chunk, encoding), 'utf8', callback)
28
+ }
29
+ stream.end = function (chunk, encoding, callback) {
30
+ if (typeof chunk === 'function') {
31
+ callback = chunk
32
+ chunk = undefined
33
+ } else if (typeof encoding === 'function') {
34
+ callback = encoding
35
+ encoding = undefined
36
+ }
37
+ const output = chunk === undefined || chunk === null ? '' : consume(chunk, encoding)
38
+ return end(output + flush(), 'utf8', callback)
39
+ }
40
+ stream[stateKey] = redactor
41
+ process.on('beforeExit', () => {
42
+ const output = flush()
43
+ if (output) write(output)
44
+ })
45
+ process.on('exit', () => {
46
+ const output = flush()
47
+ if (output) {
48
+ try { fs.writeSync(stream.fd, output) } catch { /* The destination may already be closed. */ }
49
+ }
50
+ })
51
+ }
52
+
53
+ module.exports = function redactProcessOutput (secrets) {
54
+ const values = secrets.filter(value => typeof value === 'string' && value.length > 0)
55
+ if (!values.length) return
56
+ install(process.stdout, values)
57
+ install(process.stderr, values)
58
+ }
@@ -6,7 +6,7 @@ function redactedValues (processedEnvs, schema, processEnv = {}, legacyRedact =
6
6
 
7
7
  const rows = [...(processedEnvs || [])]
8
8
  if (schema?.exists) {
9
- rows.push({ injected: Object.fromEntries([...schema.redactionRules.keys()].map(key => [key, processEnv[key]])) })
9
+ rows.push({ injected: Object.fromEntries(Object.keys(schema.keys).map(key => [key, processEnv[key]])) })
10
10
  }
11
11
  for (const processedEnv of rows) {
12
12
  const values = {
@@ -15,7 +15,7 @@ function redactedValues (processedEnvs, schema, processEnv = {}, legacyRedact =
15
15
  }
16
16
 
17
17
  for (const [key, value] of Object.entries(values)) {
18
- const redacted = schema?.exists ? (schema.redactionRules.get(key) ?? schema.redacted) : !isPublicKey(key)
18
+ const redacted = schema?.exists ? (schema.keys[key]?.stdio.redacted ?? true) : !isPublicKey(key)
19
19
  if (!redacted) continue
20
20
  if (value === undefined || value === null || value === '') continue
21
21
 
@@ -0,0 +1,29 @@
1
+ const { profile } = require('@dotenvx/primitives')
2
+ const readEnvfile = require('../envfile/parsing/readEnvfile')
3
+ const normalizeDotenvConfigPath = require('./normalizeDotenvConfigPath')
4
+ const buildCommandEnvs = require('./buildCommandEnvs')
5
+ const determine = require('./envResolution/determine')
6
+
7
+ module.exports = function selectEnvfileEnvs (envs = [], options = {}, processEnv = process.env) {
8
+ const resolve = values => options.resolveDirectories === false ? values : buildCommandEnvs(values, options.convention)
9
+ const document = readEnvfile.source()
10
+ if (!document.exists) {
11
+ if (options.profile !== undefined) throw new Error('Profile selection requires an Envfile')
12
+ return determine(resolve(normalizeDotenvConfigPath(envs, processEnv)), processEnv)
13
+ }
14
+ // Keep explicit CLI file/inline-env ordering; profiles only supply file selection.
15
+ const explicit = resolve(envs)
16
+ const files = explicit.filter(env => env.type === 'envFile')
17
+ let selected
18
+ try {
19
+ selected = profile(document.source, {
20
+ f: files.length ? files.map(env => env.value).join(',') : undefined,
21
+ profile: options.profile,
22
+ processEnv
23
+ })
24
+ } catch (error) {
25
+ throw readEnvfile.formatError(error, document)
26
+ }
27
+ if (files.length) return explicit
28
+ return resolve((selected ? selected.split(',').map(value => ({ type: 'envFile', value })) : []).concat(explicit))
29
+ }
package/src/lib/main.d.ts CHANGED
@@ -86,6 +86,9 @@ export interface DotenvConfigOptions {
86
86
  */
87
87
  path?: string | string[] | URL;
88
88
 
89
+ /** Select a named Envfile profile when no explicit paths are supplied. */
90
+ profile?: string;
91
+
89
92
  /**
90
93
  * Specify the encoding of your file containing environment variables.
91
94
  *
@@ -110,7 +113,7 @@ export interface DotenvConfigOptions {
110
113
 
111
114
  /**
112
115
  * Throw immediately if an error is encountered - like a missing .env file.
113
- * Includes Dotenvspec validation failures. Dotenvspec strict settings also enforce throwing.
116
+ * Includes Envfile validation failures. Envfile strict settings also enforce throwing.
114
117
  * @default false
115
118
  * @example require('@dotenvx/dotenvx').config({ strict: true })
116
119
  */
@@ -256,11 +259,11 @@ export interface DotenvPopulateInput {
256
259
 
257
260
  /**
258
261
  * Loads `.env` file contents into process.env by default.
259
- * Reads Dotenvspec from the current directory and validates the final resolved environment.
260
- * Falls back to Envspec, then Dotenvxspec, when earlier filenames are absent.
261
- * DOTENV_SPEC in processEnv (process.env by default) overrides files with inline policy text.
262
+ * Reads Envfile from the current directory and validates the final resolved environment.
262
263
  * Validation failures warn and return an error, or throw when strictness is enabled.
263
- * Invalid Dotenvspec syntax and active proxy rules always throw; use run for proxy support.
264
+ * Invalid Envfile syntax always throws.
265
+ * With an Envfile, subsequent Node stdout/stderr writes are automatically redacted.
266
+ * Environment and returned values remain unchanged; native writes and inherited child output bypass redaction.
264
267
  *
265
268
  * @see https://dotenvx.com/docs
266
269
  *
@@ -281,6 +284,9 @@ export interface SetOptions {
281
284
  */
282
285
  path?: string | string[] | URL;
283
286
 
287
+ /** Select a named Envfile profile when no explicit paths are supplied. */
288
+ profile?: string;
289
+
284
290
  /**
285
291
  * Customize the path to your .env.keys file. This is useful with monorepos.
286
292
  * @default []
@@ -375,6 +381,9 @@ export interface GetOptions {
375
381
  */
376
382
  path?: string | string[] | URL;
377
383
 
384
+ /** Select a named Envfile profile when no explicit paths are supplied. */
385
+ profile?: string;
386
+
378
387
  /**
379
388
  * Mask returned values, optionally setting the number of visible characters.
380
389
  * @default false
package/src/lib/main.js CHANGED
@@ -19,7 +19,6 @@ const setTransform = require('./transforms/set')
19
19
  // helpers
20
20
  const buildEnvs = require('./helpers/buildEnvs')
21
21
  const buildConfigEnvs = require('./helpers/buildConfigEnvs')
22
- const { determine } = require('./helpers/envResolution')
23
22
  const escape = require('./helpers/escape')
24
23
  const fsx = require('./helpers/fsx')
25
24
  const decryptKeyValue = require('./helpers/cryptography/decryptKeyValue')
@@ -27,12 +26,13 @@ const Errors = require('./helpers/errors')
27
26
  const normalizeDotenvConfigQuiet = require('./helpers/normalizeDotenvConfigQuiet')
28
27
  const normalizeDotenvConfigConvention = require('./helpers/normalizeDotenvConfigConvention')
29
28
  const normalizeDotenvConfigIgnore = require('./helpers/normalizeDotenvConfigIgnore')
30
- const normalizeDotenvConfigPath = require('./helpers/normalizeDotenvConfigPath')
29
+ const selectEnvfileEnvs = require('./helpers/selectEnvfileEnvs')
31
30
  const mask = require('./helpers/mask')
32
31
  const maskProcessedEnvs = require('./helpers/maskProcessedEnvs')
33
- const readEnvspec = require('./envspec/parsing/readEnvspec')
34
- const validateEnvspec = require('./envspec/validation/validateEnvspec')
32
+ const readEnvfile = require('./envfile/parsing/readEnvfile')
33
+ const validateEnvfile = require('./envfile/validation/validateEnvfile')
35
34
  const redactedValues = require('./helpers/redactedValues')
35
+ const redactProcessOutput = require('./helpers/redactProcessOutput')
36
36
  const { redactOutput } = require('./helpers/redactOutput')
37
37
 
38
38
  function uniqueInjectedKeys (processedEnvs) {
@@ -82,15 +82,8 @@ const config = function (options = {}, events) {
82
82
  let fatal = false
83
83
  let sensitiveValues = []
84
84
  try {
85
- let envs = normalizeDotenvConfigPath(buildConfigEnvs(options))
86
- if (!options.envs) {
87
- envs = determine(envs, processEnv)
88
- }
89
- const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value), processEnv)
90
- if (schema.proxyRules.size > 0) {
91
- fatal = true
92
- throw new Error('Dotenvspec proxy is not supported by synchronous config(). Use dotenvx run -- yourcommand.')
93
- }
85
+ const envs = options.envs || selectEnvfileEnvs(buildConfigEnvs(options), { ...options, convention: undefined }, { ...process.env, ...processEnv })
86
+ const schema = readEnvfile(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
94
87
  const {
95
88
  processedEnvs,
96
89
  readableFilepaths
@@ -108,8 +101,9 @@ const config = function (options = {}, events) {
108
101
  token: options.token
109
102
  })
110
103
 
111
- const validationError = validateEnvspec(schema, processEnv, processedEnvs)
104
+ const validationError = validateEnvfile.error(validateEnvfile(schema, processEnv).errors)
112
105
  sensitiveValues = redactedValues(processedEnvs, schema, processEnv)
106
+ if (schema.exists) redactProcessOutput(sensitiveValues)
113
107
 
114
108
  if (options.mask !== undefined) {
115
109
  const showChar = options.mask === true ? 6 : options.mask
@@ -130,10 +124,7 @@ const config = function (options = {}, events) {
130
124
  continue // ignore error
131
125
  }
132
126
 
133
- const policyStrict = processedEnv.type === 'envFile'
134
- ? (schema.strictByFile?.get(path.resolve(processedEnv.filepath)) ?? schema.strict)
135
- : schema.strict
136
- if (strict || policyStrict) {
127
+ if (strict) {
137
128
  fatal = true
138
129
  throw error
139
130
  }
@@ -195,7 +186,7 @@ const config = function (options = {}, events) {
195
186
  }
196
187
  } catch (error) {
197
188
  if (events) events.fail(error)
198
- if (strict || fatal || error.code === 'MALFORMED_ENVSPEC') throw error
189
+ if (strict || fatal || error.code === 'MALFORMED_ENVFILE') throw error
199
190
 
200
191
  logger.error(redactOutput(error.messageWithHelp || error.message, sensitiveValues))
201
192
 
@@ -288,6 +279,7 @@ const set = async function (key, value, options = {}, events) {
288
279
  unchangedFilepaths
289
280
  } = await setTransform({
290
281
  envs,
282
+ profile: options.profile,
291
283
  key,
292
284
  value,
293
285
  fk: envKeysFilepath,
@@ -372,8 +364,10 @@ const get = async function (key, options = {}, events) {
372
364
  const ignore = options.ignore || []
373
365
 
374
366
  const { parsed, errors } = await getResolver({
367
+ resolveDirectories: false,
375
368
  key,
376
369
  envs,
370
+ profile: options.profile,
377
371
  overload: options.overload,
378
372
  all: options.all,
379
373
  envKeysFile: options.envKeysFile,
@@ -54,13 +54,11 @@ function inject (processEnv, parsed) {
54
54
  }
55
55
  }
56
56
 
57
- function buildParseOptions ({ lockPassword, processEnv, overload, envKeysFilepath, provider, decryptor, proxyCredentials, proxyRules }) {
57
+ function buildParseOptions ({ lockPassword, processEnv, overload, envKeysFilepath, provider, decryptor }) {
58
58
  const options = {
59
59
  lockPassword,
60
60
  processEnv,
61
61
  overload,
62
- proxyCredentials,
63
- proxyRules,
64
62
  fk: envKeysFilepath
65
63
  }
66
64
 
@@ -77,7 +75,7 @@ function buildParseOptions ({ lockPassword, processEnv, overload, envKeysFilepat
77
75
  return options
78
76
  }
79
77
 
80
- async function injectEnv ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, no1Password, noBitwarden, onStatus, proxyCredentials, proxyRules }) {
78
+ async function injectEnv ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, no1Password, noBitwarden, onStatus }) {
81
79
  const row = {}
82
80
  row.type = TYPE_ENV
83
81
  row.string = env.value
@@ -94,9 +92,7 @@ async function injectEnv ({ env, lockPassword, overload, processEnv, envKeysFile
94
92
  lockPassword,
95
93
  envKeysFilepath,
96
94
  provider,
97
- decryptor,
98
- proxyCredentials,
99
- proxyRules
95
+ decryptor
100
96
  })
101
97
 
102
98
  const {
@@ -186,7 +182,7 @@ function injectEnvSync ({ env, lockPassword, overload, processEnv, envKeysFilepa
186
182
  return row
187
183
  }
188
184
 
189
- async function injectEnvFile ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, readableFilepaths, no1Password, noBitwarden, onStatus, proxyCredentials, proxyRules }) {
185
+ async function injectEnvFile ({ env, lockPassword, overload, processEnv, envKeysFilepath, provider, decryptor, readableFilepaths, no1Password, noBitwarden, onStatus }) {
190
186
  const row = {}
191
187
  row.type = TYPE_ENV_FILE
192
188
  row.filepath = env.value
@@ -205,9 +201,7 @@ async function injectEnvFile ({ env, lockPassword, overload, processEnv, envKeys
205
201
  lockPassword,
206
202
  envKeysFilepath: fk,
207
203
  provider,
208
- decryptor,
209
- proxyCredentials,
210
- proxyRules
204
+ decryptor
211
205
  })
212
206
 
213
207
  const {
@@ -331,8 +325,6 @@ async function envs (options = {}) {
331
325
  readableFilepaths,
332
326
  no1Password,
333
327
  noBitwarden,
334
- proxyCredentials: options.proxyCredentials,
335
- proxyRules: options.proxyRules,
336
328
  onStatus: options.onStatus
337
329
  }))
338
330
  } else if (env.type === TYPE_ENV) {
@@ -346,8 +338,6 @@ async function envs (options = {}) {
346
338
  decryptor,
347
339
  no1Password,
348
340
  noBitwarden,
349
- proxyCredentials: options.proxyCredentials,
350
- proxyRules: options.proxyRules,
351
341
  onStatus: options.onStatus
352
342
  }))
353
343
  }
@@ -1,6 +1,6 @@
1
1
  const envsResolver = require('./envs')
2
2
  const Errors = require('./../helpers/errors')
3
- const { determine } = require('./../helpers/envResolution')
3
+ const selectEnvfileEnvs = require('../helpers/selectEnvfileEnvs')
4
4
 
5
5
  function collectErrors (processedEnvs) {
6
6
  const errors = []
@@ -45,7 +45,7 @@ function result ({ key, all, processedEnvs, processEnv }) {
45
45
 
46
46
  function buildOptions (options, processEnv) {
47
47
  return {
48
- envs: determine(options.envs || [], processEnv),
48
+ envs: selectEnvfileEnvs(options.envs, options, processEnv),
49
49
  overload: options.overload,
50
50
  processEnv,
51
51
  envKeysFilepath: options.envKeysFilepath || options.envKeysFile || null,
@@ -2,8 +2,8 @@ const fs = require('node:fs')
2
2
  const path = require('node:path')
3
3
  const { scan, encrypted } = require('@dotenvx/primitives')
4
4
 
5
- const normalizeEnvspec = require('../envspec/rendering/normalizeEnvspec')
6
- const renderEnvspec = require('../envspec/rendering/renderEnvspec')
5
+ const normalizeEnvfile = require('../envfile/rendering/normalizeEnvfile')
6
+ const renderEnvfile = require('../envfile/rendering/renderEnvfile')
7
7
  const isPublicKey = require('../helpers/isPublicKey')
8
8
 
9
9
  function declaration (name) {
@@ -15,10 +15,10 @@ function declaration (name) {
15
15
  }
16
16
 
17
17
  module.exports = function init ({ directory = process.cwd(), envFile, envFiles, sourceKeys = [], overwrite = false, stdout = false, onFile = () => {} } = {}) {
18
- const target = path.resolve(directory, 'Dotenvspec')
18
+ const target = path.resolve(directory, 'Envfile')
19
19
  const existing = stdout ? undefined : fs.lstatSync(target, { throwIfNoEntry: false })
20
20
  if (existing && !overwrite) return { created: false }
21
- if (existing && !existing.isFile()) throw new Error(`Cannot replace Dotenvspec: expected a regular file (${target})`)
21
+ if (existing && !existing.isFile()) throw new Error(`Cannot replace Envfile: expected a regular file (${target})`)
22
22
  const seen = new Set()
23
23
 
24
24
  const sources = []
@@ -61,10 +61,10 @@ module.exports = function init ({ directory = process.cwd(), envFile, envFiles,
61
61
  const addedFromSource = names.size - inputCount
62
62
  const keys = [...names]
63
63
  const invalid = keys.filter(key => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
64
- if (invalid.length) throw new Error(`Unsupported Dotenvspec variable names: ${invalid.join(', ')}`)
64
+ if (invalid.length) throw new Error(`Unsupported Envfile variable names: ${invalid.join(', ')}`)
65
65
 
66
- const document = normalizeEnvspec({ files, codeDeclarations })
67
- const content = renderEnvspec(document)
66
+ const document = normalizeEnvfile({ files, codeDeclarations })
67
+ const content = renderEnvfile(document)
68
68
  if (stdout) return { created: false, content }
69
69
  try {
70
70
  fs.writeFileSync(target, content, { flag: overwrite ? fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | fs.constants.O_NOFOLLOW : 'wx' })
@@ -1,37 +1,30 @@
1
1
  const envsResolver = require('../resolvers/envs')
2
2
  const Session = require('../../db/session')
3
- const buildCommandEnvs = require('../helpers/buildCommandEnvs')
4
- const resolveEnvKeysFile = require('../helpers/resolveEnvKeysFile')
5
- const readEnvspec = require('../envspec/parsing/readEnvspec')
6
- const validateEnvspec = require('../envspec/validation/validateEnvspec')
3
+ const selectEnvfileEnvs = require('../helpers/selectEnvfileEnvs')
7
4
  const normalizeDotenvConfigPath = require('../helpers/normalizeDotenvConfigPath')
5
+ const resolveEnvKeysFile = require('../helpers/resolveEnvKeysFile')
6
+ const readEnvfile = require('../envfile/parsing/readEnvfile')
7
+ const validateEnvfile = require('../envfile/validation/validateEnvfile')
8
8
  const Errors = require('../helpers/errors')
9
- const { determine } = require('../helpers/envResolution')
10
9
  const path = require('node:path')
11
10
  const resolveDirectoryFilepath = require('../helpers/resolveDirectoryFilepath')
12
11
 
13
12
  // Load once and validate the final values; callers own presentation and execution.
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 => {
13
+ module.exports = async function validate ({ envs = [], options = {}, processEnv = { ...process.env }, requireEnvfile = true, command, onStatus } = {}) {
14
+ const explicitEnvs = options.profile ? envs : normalizeDotenvConfigPath(envs, processEnv)
15
+ const requiredFilepaths = new Set(explicitEnvs.filter(env => env.type === 'envFile').flatMap(env => {
17
16
  const resolved = resolveDirectoryFilepath(env.value, '.env')
18
17
  // A directory with a convention selects optional layers rather than one file.
19
18
  return options.convention && resolved !== env.value ? [] : [path.resolve(resolved)]
20
19
  }))
21
- envs = buildCommandEnvs(envs, options.convention)
22
- envs = determine(envs, processEnv)
23
- const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value), processEnv)
24
- if (requireEnvspec && !schema.exists) throw new Errors().envspecRequired()
20
+ envs = selectEnvfileEnvs(envs, options, processEnv)
21
+ const schema = readEnvfile(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
22
+ if (requireEnvfile && !schema.exists) throw new Errors().envfileRequired()
25
23
 
26
24
  const session = new Session()
27
- const proxyToken = options.token || processEnv.DOTENVX_TOKEN
28
- const noArmor = options.armor === false || (!proxyToken && (await session.noArmor()))
29
- if (schema.proxyRules.size > 0 && noArmor) throw new Error('Dotenvspec proxy requires Armor. Enable Armor and authenticate before running.')
30
- const proxyCredentials = noArmor ? undefined : []
25
+ const noArmor = options.armor === false || (!(options.token || processEnv.DOTENVX_TOKEN) && (await session.noArmor()))
31
26
  const { processedEnvs, readableFilepaths } = await envsResolver({
32
27
  envs,
33
- proxyRules: schema.proxyRules,
34
- proxyCredentials,
35
28
  overload: options.overload,
36
29
  processEnv,
37
30
  envKeysFile: resolveEnvKeysFile(options.envKeysFile),
@@ -45,25 +38,21 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
45
38
  onStatus
46
39
  })
47
40
 
48
- let proxyError
49
- for (const name of schema.proxyRules.keys()) {
50
- if (processEnv[name] !== undefined && !(proxyCredentials || []).some(credential => credential.name === name && credential.placeholder === processEnv[name])) {
51
- proxyError = new Error(`Dotenvspec proxy requires an encrypted ${name} loaded from an env file. Remove plaintext or shell overrides, or use --overload.`)
52
- break
53
- }
54
- }
41
+ const keys = new Set([
42
+ ...Object.keys(schema.keys),
43
+ ...processedEnvs.flatMap(row => Object.keys(row.parsed || {}))
44
+ ])
45
+ const finalEnv = Object.fromEntries([...keys].filter(key => Object.hasOwn(processEnv, key)).map(key => [key, processEnv[key]]))
46
+ const result = validateEnvfile(schema, finalEnv)
55
47
 
56
48
  return {
57
49
  processEnv,
58
50
  processedEnvs,
59
51
  readableFilepaths,
60
52
  requiredFilepaths,
61
- hasEnvspec: schema.exists,
53
+ hasEnvfile: schema.exists,
62
54
  schema,
63
- proxyCredentials,
64
- proxyToken,
65
- session,
66
- proxyError,
67
- validationError: validateEnvspec(schema, processEnv, processedEnvs, onKey)
55
+ checked: result.checked,
56
+ validationError: validateEnvfile.error(result.errors)
68
57
  }
69
58
  }
@@ -6,13 +6,13 @@ const TYPE_ENV_FILE = 'envFile'
6
6
  const SAMPLE_ENV_KIT = require('../helpers/kits/sample')
7
7
 
8
8
  const Errors = require('../helpers/errors')
9
- const { determine } = require('./../helpers/envResolution')
9
+ const selectEnvfileEnvs = require('../helpers/selectEnvfileEnvs')
10
10
  const detectEncoding = require('./../helpers/detectEncoding')
11
11
  const { isDotenvPublicKey, isPlainKey, mutateSrc } = require('../helpers/cryptography')
12
12
  const keynames = require('../conventions/keynames')
13
13
 
14
14
  const storeKeyStorage = require('../helpers/storeKeyStorage')
15
- const readEnvspec = require('../envspec/parsing/readEnvspec')
15
+ const readEnvfile = require('../envfile/parsing/readEnvfile')
16
16
 
17
17
  async function encryptTransform (options = {}) {
18
18
  const envs = options.envs || []
@@ -42,7 +42,7 @@ async function encryptTransform (options = {}) {
42
42
  }
43
43
  }
44
44
 
45
- for (const env of determine(envs, process.env)) {
45
+ for (const env of selectEnvfileEnvs(envs, options)) {
46
46
  if (env.type !== TYPE_ENV_FILE) {
47
47
  continue
48
48
  }
@@ -52,7 +52,7 @@ async function encryptTransform (options = {}) {
52
52
  const row = { keys: [], type: TYPE_ENV_FILE, filepath, envFilepath, changed: false }
53
53
 
54
54
  try {
55
- const schema = readEnvspec(undefined, [filepath])
55
+ const schema = readEnvfile(undefined, [filepath])
56
56
  const fileExists = await fsx.exists(filepath)
57
57
  if (!fileExists && !noCreate) {
58
58
  row.envSrc = SAMPLE_ENV_KIT
@@ -70,7 +70,7 @@ async function encryptTransform (options = {}) {
70
70
  const { parsed } = scan(row.envSrc, { ik, ek })
71
71
  const selected = Object.entries(parsed).filter(([key]) => {
72
72
  if (isDotenvPublicKey(key)) return false
73
- return schema.exists ? (schema.encryptionRules.get(key) ?? schema.encrypted) : !isPlainKey(key)
73
+ return schema.exists ? (schema.keys[key]?.fs.encrypted ?? true) : !isPlainKey(key)
74
74
  })
75
75
  if (schema.exists && !selected.some(([, values]) => values.some(value => !encrypted(value)))) {
76
76
  // A missing file still needs writing even when its initial values are
@@ -5,7 +5,8 @@ const { encrypt, upsert, publickeys, keypair } = require('@dotenvx/primitives')
5
5
  const TYPE_ENV_FILE = 'envFile'
6
6
 
7
7
  const getResolver = require('./../resolvers/get')
8
- const { determine } = require('./../helpers/envResolution')
8
+ const selectEnvfileEnvs = require('../helpers/selectEnvfileEnvs')
9
+ const readEnvfile = require('../envfile/parsing/readEnvfile')
9
10
  const detectEncoding = require('./../helpers/detectEncoding')
10
11
  const { isPlainKey, mutateSrc } = require('../helpers/cryptography')
11
12
  const keynames = require('../conventions/keynames')
@@ -23,7 +24,6 @@ async function setTransform (options = {}) {
23
24
  const custodyContext = { token: options.token }
24
25
  const noNative = options.noNative
25
26
  const noCreate = options.noCreate
26
- const noEncrypt = !options.encrypt || isPlainKey(key)
27
27
 
28
28
  const processedEnvs = []
29
29
  const changedFilepaths = []
@@ -44,7 +44,7 @@ async function setTransform (options = {}) {
44
44
  }
45
45
  }
46
46
 
47
- for (const env of determine(envs, process.env)) {
47
+ for (const env of selectEnvfileEnvs(envs, options)) {
48
48
  if (env.type !== TYPE_ENV_FILE) {
49
49
  continue
50
50
  }
@@ -54,6 +54,8 @@ async function setTransform (options = {}) {
54
54
  const row = { key, value, type: TYPE_ENV_FILE, filepath, envFilepath, changed: false }
55
55
 
56
56
  try {
57
+ const schema = readEnvfile(undefined, [filepath])
58
+ const noEncrypt = !options.encrypt || (schema.exists ? schema.keys[key]?.fs.encrypted === false : isPlainKey(key))
57
59
  const fileExists = await fsx.exists(filepath)
58
60
  if (!fileExists && !noCreate) {
59
61
  row.envSrc = ''
@@ -1,105 +0,0 @@
1
- Document
2
- = _ entries:((FileBlock / Declaration / Strict) _)* {
3
- const items = entries.map(item => item[0]);
4
- const settings = items.filter(item => item.strict !== undefined && !item.file);
5
- if (settings.length > 1) error("Duplicate Dotenvspec setting: strict");
6
- return { ...settings[0], declarations: items.filter(item => item.name), files: items.filter(item => item.file) };
7
- }
8
-
9
- FileBlock
10
- = "file" [ \t]+ file:Filename [ \t]+ "do" [ \t]* Comment? Newline _ entries:((Declaration / Strict) _)* "end" [ \t]* Comment? (Newline / !.) {
11
- const items = entries.map(item => item[0]);
12
- const settings = items.filter(item => item.strict !== undefined);
13
- if (settings.length > 1) error("Duplicate Dotenvspec setting: strict");
14
- return { file, ...settings[0], declarations: items.filter(item => item.name) };
15
- }
16
-
17
- Strict
18
- = "strict" [ \t]+ value:Boolean [ \t]* Comment? (Newline / !.) { return { strict: value }; }
19
-
20
- Filename "a quoted filename"
21
- = '"' value:$([^"\r\n\0]+) '"' { return value; }
22
- / "'" value:$([^'\r\n\0]+) "'" { return value; }
23
-
24
- Declaration
25
- = "env" [ \t]+ name:Name options:Option* [ \t]* Comment? (Newline / !.) {
26
- const declaration = { name };
27
- const seen = new Set();
28
- for (const option of options) {
29
- if (seen.has(option.key)) error(`Duplicate Dotenvspec option: ${option.key}`);
30
- if ((option.key === "optional" && seen.has("required")) ||
31
- (option.key === "required" && seen.has("optional"))) {
32
- error("Cannot combine required and optional in a Dotenvspec declaration");
33
- }
34
- seen.add(option.key);
35
- if (option.key === "optional") declaration.required = !option.value;
36
- else declaration[option.key] = option.value;
37
- }
38
- return declaration;
39
- }
40
-
41
- Option
42
- = [ \t]* "," _ "proxy" [ \t]* ":" _ value:(ProxyOptions / Disabled) { return { key: "proxy", value }; }
43
- / [ \t]* "," _ "required" [ \t]* ":" _ value:Boolean { return { key: "required", value }; }
44
- / [ \t]* "," _ "optional" [ \t]* ":" _ value:Boolean { return { key: "optional", value }; }
45
- / [ \t]* "," _ ("redacted" / "redact") [ \t]* ":" _ value:Boolean { return { key: "redacted", value }; }
46
- / [ \t]* "," _ ("encrypted" / "encrypt") [ \t]* ":" _ value:Boolean { return { key: "encrypted", value }; }
47
- / [ \t]* "," _ "type" [ \t]* ":" _ value:Type { return { key: "type", value }; }
48
- / [ \t]* "," _ "enum" [ \t]* ":" _ value:Enum { return { key: "enum", value }; }
49
- / [ \t]* "," _ key:("min" / "max") [ \t]* ":" _ value:Integer { return { key, value }; }
50
-
51
- Integer "an integer"
52
- = value:$([+-]? [0-9]+) { return value; }
53
-
54
- Enum
55
- = "[" _ first:EnumValue rest:(_ "," _ value:EnumValue { return value; })* _ ","? _ "]" {
56
- return [first, ...rest];
57
- }
58
-
59
- EnumValue
60
- = '"' chars:(Escape / [^"\\\r\n])* '"' { return chars.join(""); }
61
- / "'" chars:(Escape / [^'\\\r\n])* "'" { return chars.join(""); }
62
- / Integer
63
-
64
- Escape
65
- = "\\" char:["'\\nrt] {
66
- return ({ n: "\n", r: "\r", t: "\t" })[char] || char;
67
- }
68
-
69
- Type "a supported type (integer, boolean, port, url, email, or ip)"
70
- = ('"integer"' / "'integer'") { return "integer"; }
71
- / ('"boolean"' / "'boolean'") { return "boolean"; }
72
- / ('"port"' / "'port'") { return "port"; }
73
- / ('"url"' / "'url'") { return "url"; }
74
- / ('"email"' / "'email'") { return "email"; }
75
- / ('"ip"' / "'ip'") { return "ip"; }
76
-
77
- Boolean "true or false"
78
- = "true" { return true; }
79
- / Disabled
80
-
81
- ProxyOptions
82
- = "{" _ "domain" [ \t]* ":" _ domain:Destination _ ","? _ "}" { return { domain }; }
83
-
84
- Disabled
85
- = "false" { return false; }
86
-
87
- Destination "a quoted domain"
88
- = '"' host:$([A-Za-z0-9.-]+) '"' { return host; }
89
- / "'" host:$([A-Za-z0-9.-]+) "'" { return host; }
90
-
91
- Name "a quoted variable name"
92
- = '"' name:Identifier '"' { return name; }
93
- / "'" name:Identifier "'" { return name; }
94
-
95
- Identifier
96
- = $([A-Za-z_] [A-Za-z0-9_]*)
97
-
98
- Comment
99
- = "#" [^\r\n]*
100
-
101
- Newline
102
- = "\r\n" / "\n" / "\r"
103
-
104
- _
105
- = ([ \t] / Newline / Comment)*