@dotenvx/dotenvx 2.32.4 → 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 +13 -1
  2. package/README.md +24 -25
  3. package/package.json +3 -11
  4. package/src/cli/actions/check.js +6 -11
  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 +4 -4
  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 +5 -0
  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} +3 -3
  26. package/src/lib/{envspec/validation/protectEnvspec.js → envfile/validation/protectEnvfile.js} +7 -7
  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 +12 -2
  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 +4 -4
  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 -144
  46. package/src/lib/envspec/parsing/resolveEnvspecPath.js +0 -11
  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
@@ -70,11 +70,9 @@ function parseResponse (value) {
70
70
  async function available () {
71
71
  try {
72
72
  const version = await run(['--version'], undefined, 2000)
73
- if (!/^2\./.test(version.trim())) return false
74
- if (process.env.OP_SERVICE_ACCOUNT_TOKEN) return true
75
- // Account discovery is local; authenticate only after the user selects 1Password.
76
- const accounts = parseResponse(await run(['account', 'list', '--format=json'], undefined, 2000))
77
- return Array.isArray(accounts) && accounts.length > 0
73
+ // Availability means the CLI is installed. Account setup and authentication
74
+ // are checked by set() only after the user selects 1Password.
75
+ return /^2\./.test(version.trim())
78
76
  } catch {
79
77
  return false
80
78
  }
@@ -11,7 +11,7 @@ module.exports = function discoverEnvFiles ({ directory = process.cwd() } = {})
11
11
  function walk (current) {
12
12
  const entries = fs.readdirSync(current, { withFileTypes: true })
13
13
  // Stop at nested packages and initialized projects, including symlinked markers.
14
- if (current !== root && entries.some(entry => ['Envfile', 'Envspec', 'Dotenvspec', 'package.json'].includes(entry.name))) return
14
+ if (current !== root && entries.some(entry => ['Envfile', 'package.json'].includes(entry.name))) return
15
15
  for (const entry of entries) {
16
16
  const filename = path.join(current, entry.name)
17
17
  if (entry.isDirectory()) {
@@ -4,7 +4,7 @@ const { ignore } = require('@dotenvx/tooling')
4
4
  const extractEnvKeys = require('./extractEnvKeys')
5
5
 
6
6
  const ignoredDirectories = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'vendor', '.venv', 'coverage', '__pycache__'])
7
- const projectMarkers = new Set(['package.json', 'Envfile', 'Envspec', 'Dotenvspec', '.env.schema'])
7
+ const projectMarkers = new Set(['package.json', 'Envfile', '.env.schema'])
8
8
  const languages = {
9
9
  js: 'js',
10
10
  mjs: 'js',
@@ -1,6 +1,6 @@
1
1
  const path = require('node:path')
2
2
 
3
- module.exports = function formatEnvspecSyntaxError (error, src, filepath) {
3
+ module.exports = function formatEnvfileSyntaxError (error, src, filepath) {
4
4
  const location = error.location?.start
5
5
  if (!location) return error.message
6
6
 
@@ -0,0 +1,43 @@
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+ const { policy } = require('@dotenvx/primitives')
4
+ const resolveEnvfilePath = require('./resolveEnvfilePath')
5
+ const formatEnvfileSyntaxError = require('./formatEnvfileSyntaxError')
6
+
7
+ function readSource (filepath = resolveEnvfilePath()) {
8
+ try {
9
+ return { source: fs.readFileSync(filepath, 'utf8'), filepath, exists: true }
10
+ } catch (error) {
11
+ if (error.code !== 'ENOENT') throw error
12
+ if (fs.lstatSync(filepath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envfile: ${filepath}`)
13
+ return { filepath, exists: false }
14
+ }
15
+ }
16
+
17
+ function readEnvfile (filepath, files = ['.env']) {
18
+ const document = readSource(filepath)
19
+ if (!document.exists) return { keys: {}, exists: false }
20
+ // File paths arrive relative to the caller; file blocks are relative to Envfile.
21
+ const selected = files.flatMap(file => {
22
+ const absolute = path.resolve(file)
23
+ return [path.relative(path.dirname(document.filepath), absolute), absolute]
24
+ }).join(',')
25
+ try {
26
+ return { ...policy(document.source, selected), exists: true }
27
+ } catch (error) {
28
+ formatError(error, document)
29
+ throw error
30
+ }
31
+ }
32
+
33
+ module.exports = readEnvfile
34
+ module.exports.source = readSource
35
+
36
+ function formatError (error, document) {
37
+ if (error.location) {
38
+ error.message = `[${error.code}] ${formatEnvfileSyntaxError(error.cause || error, document.source, document.filepath)}`
39
+ error.messageWithHelp = error.message
40
+ }
41
+ return error
42
+ }
43
+ module.exports.formatError = formatError
@@ -0,0 +1,5 @@
1
+ const path = require('node:path')
2
+
3
+ module.exports = function resolveEnvfilePath (directory = process.cwd()) {
4
+ return path.resolve(directory, 'Envfile')
5
+ }
@@ -1,5 +1,5 @@
1
1
  // Pure final pass over independently inferred file rules. Never mutates inputs.
2
- module.exports = function normalizeEnvspec ({ files, codeDeclarations = [] }) {
2
+ module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
3
3
  const hasNamedEnvironment = files.some(file => !['.env', '.env.example'].includes(file.filename))
4
4
  const rootFiles = []
5
5
  const environments = []
@@ -9,33 +9,25 @@ function displayValue (value) {
9
9
  }
10
10
 
11
11
  // Show final resolved values once, not source contents or unrelated shell variables.
12
- module.exports = function previewEnvspec (processedEnvs, schema, processEnv, proxyCredentials = [], diagnostics = []) {
12
+ module.exports = function previewEnvfile (processedEnvs, schema, checked, diagnostics = []) {
13
13
  const keys = new Set((processedEnvs || []).flatMap(row => [...Object.keys(row.parsed || {}), ...Object.keys(row.injected || {}), ...Object.keys(row.existed || {})]))
14
- for (const key of schema.redactionRules.keys()) keys.add(key)
15
- const proxyKeys = new Set(proxyCredentials.map(credential => credential.name))
14
+ for (const key of Object.keys(schema.keys)) keys.add(key)
16
15
  const location = diagnosticLocations(processedEnvs || [], 'process.env', { environmentLabel: 'process.env' })
17
16
  const rows = []
18
17
  const errors = new Map()
19
18
  for (const diagnostic of diagnostics) {
20
19
  keys.add(diagnostic.key)
21
- const message = diagnostic.rule
22
- ? `!${diagnostic.rule}`
23
- : diagnostic.code === 'EXPECTED_ENCRYPTED'
24
- ? '!encrypted'
25
- : diagnostic.code === 'MISSING_REQUIRED'
26
- ? '!required'
27
- : `! ${diagnostic.message.slice(diagnostic.key.length + 1).replace(/^is /, '')}`
20
+ const message = diagnostic.rule ? `!${diagnostic.rule}` : `! ${diagnostic.message}`
28
21
  errors.set(diagnostic.key, [...new Set([...(errors.get(diagnostic.key) || []), message])])
29
22
  }
30
23
  for (const key of keys) {
31
- const missing = processEnv[key] === undefined
24
+ const missing = checked[key] === undefined
32
25
  if (/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/.test(key) || (missing && !errors.has(key))) continue
33
- const value = String(processEnv[key])
34
- const redacted = schema.redactionRules.get(key) ?? true
35
- const display = missing ? '[MISSING]' : redacted || encrypted(value) || proxyKeys.has(key) ? '[REDACTED]' : displayValue(value)
26
+ const value = String(checked[key])
27
+ const display = missing ? '[MISSING]' : displayValue(encrypted(value) ? '[REDACTED]' : value)
36
28
  const source = missing ? '' : displayValue(location(key))
37
29
  const error = errors.has(key) ? errors.get(key).join(', ') : ''
38
- const unspecced = !schema.redactionRules.has(key)
30
+ const unspecced = !Object.hasOwn(schema.keys, key)
39
31
  const status = [unspecced ? '!declared' : '', error].filter(Boolean).join(', ')
40
32
  rows.push({ assignment: `${key}=${display}`, comment: [source, status].filter(Boolean).join(' '), error, unspecced })
41
33
  }
@@ -17,8 +17,8 @@ function renderFile (file) {
17
17
  return lines.join('\n')
18
18
  }
19
19
 
20
- module.exports = function renderEnvspec (document) {
21
- const sections = []
20
+ module.exports = function renderEnvfile (document) {
21
+ const sections = ['strict true']
22
22
  if (document.declarations.length) sections.push(document.declarations.map(declaration).join('\n'))
23
23
  for (const file of document.files) {
24
24
  sections.push(renderFile(file))
@@ -26,5 +26,5 @@ module.exports = function renderEnvspec (document) {
26
26
  if (document.codeDeclarations.length) {
27
27
  sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
28
28
  }
29
- return '# Envfile (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + (sections.length ? '\n' : '')
29
+ return '# Envfile (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + '\n'
30
30
  }
@@ -1,12 +1,12 @@
1
1
  const fs = require('node:fs')
2
2
  const path = require('node:path')
3
3
  const { execFileSync } = require('node:child_process')
4
- const readEnvspec = require('../parsing/readEnvspec')
5
- const resolveEnvspecPath = require('../parsing/resolveEnvspecPath')
4
+ const readEnvfile = require('../parsing/readEnvfile')
5
+ const resolveEnvfilePath = require('../parsing/resolveEnvfilePath')
6
6
  const plaintextKeys = require('../../helpers/plaintextKeys')
7
7
 
8
8
  function readPolicy (policyPath, file) {
9
- const schema = readEnvspec(policyPath, [file])
9
+ const schema = readEnvfile(policyPath, [file])
10
10
  if (!schema.exists) {
11
11
  // A dangling policy symlink is a broken policy, not an absent policy.
12
12
  if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envfile: ${policyPath}`)
@@ -16,10 +16,10 @@ function readPolicy (policyPath, file) {
16
16
  }
17
17
 
18
18
  // Inspect Git's incoming blob, never the working-tree env values or shell overrides.
19
- module.exports = function protectEnvspec (filepath, content) {
19
+ module.exports = function protectEnvfile (filepath, content) {
20
20
  const file = path.resolve(filepath)
21
21
  const directory = path.dirname(file)
22
- let schema = readPolicy(resolveEnvspecPath(directory), file)
22
+ let schema = readPolicy(resolveEnvfilePath(directory), file)
23
23
  if (!schema) {
24
24
  let root
25
25
  try {
@@ -32,9 +32,9 @@ module.exports = function protectEnvspec (filepath, content) {
32
32
  // Outside a Git working tree, only an adjacent policy can apply.
33
33
  return null
34
34
  }
35
- if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvspecPath(root), file)
35
+ if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvfilePath(root), file)
36
36
  }
37
37
  if (!schema) return null
38
38
 
39
- return plaintextKeys(content).filter(key => /^DOTENV_PRIVATE_KEY(?:_|$)/.test(key) || (schema.encryptionRules.get(key) ?? true))
39
+ return plaintextKeys(content).filter(key => /^DOTENV_PRIVATE_KEY(?:_|$)/.test(key) || (schema.keys[key]?.fs.encrypted ?? true))
40
40
  }
@@ -0,0 +1,14 @@
1
+ const { check } = require('@dotenvx/primitives')
2
+ const Errors = require('../../helpers/errors')
3
+
4
+ module.exports = function validateEnvfile (policy, env) {
5
+ if (!policy.exists) return { checked: {}, errors: [] }
6
+ return check(policy, env)
7
+ }
8
+
9
+ module.exports.error = function validationError (diagnostics) {
10
+ if (!diagnostics.length) return
11
+ const error = new Errors({ message: diagnostics.map(item => item.message).join('; ') }).invalidEnv()
12
+ error.diagnostics = diagnostics
13
+ return error
14
+ }
@@ -233,9 +233,9 @@ class Errors {
233
233
  return e
234
234
  }
235
235
 
236
- envspecRequired () {
237
- const e = new Error('[ENVSPEC_REQUIRED] check requires an Envfile')
238
- e.code = 'ENVSPEC_REQUIRED'
236
+ envfileRequired () {
237
+ const e = new Error('[ENVFILE_REQUIRED] check requires an Envfile')
238
+ e.code = 'ENVFILE_REQUIRED'
239
239
  e.help = 'fix: run [dotenvx spec]'
240
240
  e.messageWithHelp = `${e.message}. ${e.help}`
241
241
  return e
@@ -339,15 +339,6 @@ class Errors {
339
339
  return e
340
340
  }
341
341
 
342
- malformedEnvspec () {
343
- const code = 'MALFORMED_ENVSPEC'
344
- const message = `[${code}] ${this.message}`
345
- const e = new Error(message)
346
- e.code = code
347
- e.messageWithHelp = message
348
- return e
349
- }
350
-
351
342
  invalidEnv () {
352
343
  const code = 'INVALID_ENV'
353
344
  const message = `[${code}] ${this.message}`
@@ -7,7 +7,7 @@ const { createRedactedStreamWriter, redactOutput } = require('./redactOutput')
7
7
  const ptyCommand = require('./ptyCommand')
8
8
  const { finished } = require('stream/promises')
9
9
 
10
- async function executeCommand (commandArgs, env, sensitiveValues = [], onComplete) {
10
+ async function executeCommand (commandArgs, env, sensitiveValues = []) {
11
11
  const FORWARD_SIGNAL_GRACE_MS = 1000
12
12
  const FORCE_KILL_GRACE_MS = 1000
13
13
  const signals = [
@@ -200,7 +200,6 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
200
200
  otherSignalHandlers.forEach((handler, signal) => {
201
201
  process.removeListener(signal, handler)
202
202
  })
203
- if (onComplete) await onComplete()
204
203
  }
205
204
 
206
205
  return { exitCode: commandExitCode || 0, signal: commandSignal, error: commandError }
@@ -1,5 +1,4 @@
1
- const { parse, parseSync, parsearrays, scan, encrypted } = require('@dotenvx/primitives')
2
- const prepareProxy = require('../proxy/prepareProxy')
1
+ const { parse, parseSync, parsearrays } = require('@dotenvx/primitives')
3
2
  const withLockedKeys = require('./withLockedKeys')
4
3
  const SERVER_SIDE_DECRYPTION_REQUIRED = 'SERVER_SIDE_DECRYPTION_REQUIRED'
5
4
 
@@ -29,13 +28,6 @@ function failedKeyAccessFallback (result, error) {
29
28
  }
30
29
 
31
30
  async function parseWithDecryptor (src, options = {}) {
32
- if (options.proxyCredentials) {
33
- const original = src
34
- src = prepareProxy(src, options.proxyCredentials, options.processEnv, options.proxyRules)
35
- if (src !== original && !Object.values(scan(src).parsed).flat().some(encrypted)) {
36
- options = parseOptionsWithoutProvider(options)
37
- }
38
- }
39
31
  return parseWith(src, options, parse)
40
32
  }
41
33
 
@@ -1,4 +1,4 @@
1
- const redact = require('./redact')
1
+ const { redact } = require('@dotenvx/primitives')
2
2
  const { StringDecoder } = require('string_decoder')
3
3
 
4
4
  function normalizedValues (values) {
@@ -26,11 +26,7 @@ function redactOutput (value, sensitiveValues) {
26
26
 
27
27
  if (typeof value !== 'string') return value
28
28
 
29
- let result = value
30
- for (const sensitiveValue of values) {
31
- result = result.split(sensitiveValue).join(redact(sensitiveValue))
32
- }
33
- return result
29
+ return redact(value, values)
34
30
  }
35
31
 
36
32
  function partialMatchLength (value, sensitiveValues) {
@@ -71,16 +67,35 @@ function safeBoundary (value, boundary, sensitiveValues) {
71
67
  return result
72
68
  }
73
69
 
74
- function createRedactedStreamWriter (stream, sensitiveValues, source) {
75
- const values = normalizedValues(sensitiveValues)
70
+ function createRedactor (sensitiveValues) {
71
+ const values = new Set(normalizedValues(sensitiveValues))
76
72
  const decoder = new StringDecoder('utf8')
77
73
  let pending = ''
78
- let waitingForDrain = false
74
+ return {
75
+ add: secrets => normalizedValues(secrets).forEach(secret => values.add(secret)),
76
+ write (chunk) {
77
+ pending += decoder.write(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
78
+ const secrets = [...values]
79
+ const boundary = safeBoundary(pending, pending.length - partialMatchLength(pending, secrets), secrets)
80
+ const output = redact(pending.slice(0, boundary), secrets)
81
+ pending = pending.slice(boundary)
82
+ return output
83
+ },
84
+ flush (maskPending = false) {
85
+ pending += decoder.end()
86
+ const output = maskPending && pending ? '[REDACTED]' : redact(pending, [...values])
87
+ pending = ''
88
+ return output
89
+ }
90
+ }
91
+ }
79
92
 
93
+ function createRedactedStreamWriter (stream, sensitiveValues, source) {
94
+ const redactor = createRedactor(sensitiveValues)
95
+ let waitingForDrain = false
80
96
  const writeToStream = (value) => {
81
97
  if (!value) return
82
-
83
- const canContinue = stream.write(redactOutput(value, values))
98
+ const canContinue = stream.write(value)
84
99
  if (!canContinue && source && !waitingForDrain) {
85
100
  waitingForDrain = true
86
101
  source.pause()
@@ -90,31 +105,14 @@ function createRedactedStreamWriter (stream, sensitiveValues, source) {
90
105
  })
91
106
  }
92
107
  }
93
-
94
- const flush = () => {
95
- pending += decoder.end()
96
- if (!pending) return
97
- writeToStream(pending)
98
- pending = ''
108
+ return {
109
+ write: chunk => writeToStream(redactor.write(chunk)),
110
+ flush: () => writeToStream(redactor.flush())
99
111
  }
100
-
101
- const write = (chunk) => {
102
- pending += Buffer.isBuffer(chunk) ? decoder.write(chunk) : `${chunk}`
103
-
104
- const holdbackLength = partialMatchLength(pending, values)
105
- let boundary = pending.length - holdbackLength
106
- boundary = safeBoundary(pending, boundary, values)
107
-
108
- const output = pending.slice(0, boundary)
109
- pending = pending.slice(boundary)
110
-
111
- writeToStream(output)
112
- }
113
-
114
- return { write, flush }
115
112
  }
116
113
 
117
114
  module.exports = {
118
115
  redactOutput,
116
+ createRedactor,
119
117
  createRedactedStreamWriter
120
118
  }
@@ -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
  *
@@ -257,9 +260,10 @@ export interface DotenvPopulateInput {
257
260
  /**
258
261
  * Loads `.env` file contents into process.env by default.
259
262
  * Reads Envfile from the current directory and validates the final resolved environment.
260
- * Falls back to Envspec, then Dotenvspec, when earlier filenames are absent.
261
263
  * Validation failures warn and return an error, or throw when strictness is enabled.
262
- * Invalid Envfile 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.
263
267
  *
264
268
  * @see https://dotenvx.com/docs
265
269
  *
@@ -280,6 +284,9 @@ export interface SetOptions {
280
284
  */
281
285
  path?: string | string[] | URL;
282
286
 
287
+ /** Select a named Envfile profile when no explicit paths are supplied. */
288
+ profile?: string;
289
+
283
290
  /**
284
291
  * Customize the path to your .env.keys file. This is useful with monorepos.
285
292
  * @default []
@@ -374,6 +381,9 @@ export interface GetOptions {
374
381
  */
375
382
  path?: string | string[] | URL;
376
383
 
384
+ /** Select a named Envfile profile when no explicit paths are supplied. */
385
+ profile?: string;
386
+
377
387
  /**
378
388
  * Mask returned values, optionally setting the number of visible characters.
379
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))
90
- if (schema.proxyRules.size > 0) {
91
- fatal = true
92
- throw new Error('Envfile 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,