@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
@@ -13,7 +13,6 @@ const maskEnvSrc = require('../../lib/helpers/maskEnvSrc')
13
13
  const maskProcessedEnvs = require('../../lib/helpers/maskProcessedEnvs')
14
14
  const redactedValues = require('../../lib/helpers/redactedValues')
15
15
  const { redactOutput } = require('../../lib/helpers/redactOutput')
16
- const configureProxy = require('../../lib/proxy/configureProxy')
17
16
 
18
17
  function inferCommandArgsFromProcessArgv (argv) {
19
18
  const runIndex = argv.indexOf('run')
@@ -25,7 +24,7 @@ function inferCommandArgsFromProcessArgv (argv) {
25
24
  if (separatorIndex !== -1) return args.slice(separatorIndex + 1)
26
25
 
27
26
  for (let i = 0; i < args.length; i++) {
28
- if (args[i] === '-f' || args[i] === '--file' || args[i] === '--env-file') {
27
+ if (args[i] === '-f' || args[i] === '--file' || args[i] === '--env-file' || args[i] === '--profile') {
29
28
  i++
30
29
  continue
31
30
  }
@@ -58,7 +57,6 @@ async function run () {
58
57
  }
59
58
  let commandEnv = process.env
60
59
  let sensitiveValues = []
61
- let closeProxy
62
60
 
63
61
  let commandArgs = this.args
64
62
  if (commandArgs.length < 1) {
@@ -99,26 +97,21 @@ async function run () {
99
97
  const {
100
98
  processedEnvs,
101
99
  readableFilepaths,
102
- hasEnvspec,
100
+ hasEnvfile,
103
101
  schema,
104
- proxyCredentials,
105
- proxyToken,
106
- session: sesh,
107
- proxyError,
108
102
  validationError: error
109
103
  } = await prepareValidatedEnv({
110
104
  envs: this.envs,
111
105
  options,
112
106
  processEnv: process.env,
113
- requireEnvspec: false,
107
+ requireEnvfile: false,
114
108
  command: commandArgs,
115
109
  onStatus: (text) => {
116
110
  if (spinner && text) spinner.text = text
117
111
  }
118
112
  })
119
- if (proxyError) throw proxyError
120
113
 
121
- if (hasEnvspec || options.redact === true) {
114
+ if (hasEnvfile || options.redact === true) {
122
115
  sensitiveValues = redactedValues(processedEnvs, schema, process.env, options.redact === true)
123
116
  }
124
117
 
@@ -149,10 +142,7 @@ async function run () {
149
142
  continue // ignore error
150
143
  }
151
144
 
152
- const strict = processedEnv.type === 'envFile'
153
- ? (schema.strictByFile?.get(path.resolve(processedEnv.filepath)) ?? schema.strict)
154
- : schema.strict
155
- if (options.strict || strict) throw error // throw if strict and not ignored
145
+ if (options.strict) throw error // file-loading failures use the CLI strict flag
156
146
 
157
147
  if (error.code === 'MISSING_ENV_FILE' && options.convention) { // do not output error for conventions (too noisy)
158
148
  // intentionally quiet
@@ -187,19 +177,7 @@ async function run () {
187
177
  }
188
178
  }
189
179
 
190
- const proxy = await configureProxy(commandArgs, commandEnv, proxyCredentials, sesh, proxyToken)
191
- closeProxy = proxy.close
192
- commandArgs = proxy.commandArgs
193
- commandEnv = proxy.env
194
-
195
- const gatedKeys = new Set((proxyCredentials || [])
196
- .filter(credential => commandEnv[credential.name] === credential.placeholder)
197
- .map(credential => credential.name))
198
180
  const injectedKeys = uniqueInjectedKeys(processedEnvs)
199
- for (const key of gatedKeys) {
200
- injectedKeys.delete(key)
201
- logger.verbose(`${key} proxied via Armor proxy`)
202
- }
203
181
 
204
182
  let msg = ''
205
183
  const envStringCount = processedEnvs.filter((processedEnv) => processedEnv.type === 'env' && processedEnv.parsed).length
@@ -212,10 +190,8 @@ async function run () {
212
190
  }
213
191
 
214
192
  if (spinner) spinner.stop()
215
- if (gatedKeys.size > 0) logger.success(`⧈ proxied (${gatedKeys.size})${msg}`)
216
193
  logger.success(`⟐ injected env (${injectedKeys.size})${msg}`)
217
194
  } catch (error) {
218
- if (closeProxy) await closeProxy()
219
195
  if (spinner) spinner.stop()
220
196
  if (error.code === 'PROMPT_CANCELLED') {
221
197
  return { exitCode: 130, error }
@@ -224,11 +200,7 @@ async function run () {
224
200
  return { exitCode: 1, error }
225
201
  }
226
202
 
227
- try {
228
- return await executeCommand(commandArgs, commandEnv, sensitiveValues, closeProxy)
229
- } finally {
230
- if (closeProxy) await closeProxy()
231
- }
203
+ return executeCommand(commandArgs, commandEnv, sensitiveValues)
232
204
  }
233
205
 
234
206
  module.exports = require('../../lib/events/cli')('run', run)
@@ -63,7 +63,7 @@ async function set (key, value) {
63
63
  let errorCount = 0
64
64
 
65
65
  try {
66
- const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await setTransform({ envs, key, value, fk, noArmor, token: options.token, noCreate, encrypt, noNative, no1Password, noBitwarden })
66
+ const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await setTransform({ profile: options.profile, envs, key, value, fk, noArmor, token: options.token, noCreate, encrypt, noNative, no1Password, noBitwarden })
67
67
 
68
68
  if (keysSrc) {
69
69
  await fsx.writeKeyFile(fk, keysSrc)
@@ -27,9 +27,36 @@ function output (operation, required = false) {
27
27
 
28
28
  module.exports = function primitives (command) {
29
29
  command
30
- .description('standalone primitives without env file reads or writes')
30
+ .description('standalone primitive operations')
31
31
  .action(function () { this.help() })
32
32
 
33
+ command.command('profile')
34
+ .description('resolve an Envfile profile to comma-separated filenames')
35
+ .option('--profile <name>', 'explicit profile name')
36
+ .option('-f, --file <paths>', 'explicit comma-separated files, overriding profile selection', (value, previous) => previous === undefined ? value : `${previous},${value}`)
37
+ .allowExcessArguments(false)
38
+ .action(commandAction(require('../actions/primitivesProfile')))
39
+
40
+ command.command('redact')
41
+ .description('replace secret strings in text with [REDACTED]')
42
+ .argument('[text]', 'text to redact')
43
+ .requiredOption('-s, --secret <value>', 'literal secret to redact (repeat for multiple secrets)', (value, previous) => [...(previous || []), value])
44
+ .option('--stdin', 'read text from stdin')
45
+ .allowExcessArguments(false)
46
+ .action(commandAction(require('../actions/primitivesRedact')))
47
+
48
+ command.command('policy')
49
+ .description('print the Envfile policy for selected files as JSON')
50
+ .option('-f, --file <paths>', 'comma-separated env files, first file wins (default: .env)', (value, previous) => previous === undefined ? value : `${previous},${value}`)
51
+ .allowExcessArguments(false)
52
+ .action(commandAction(require('../actions/policy')))
53
+
54
+ command.command('check')
55
+ .description('check selected env files against Envfile and print redacted JSON')
56
+ .option('-f, --file <paths>', 'comma-separated env files, first file wins (default: .env)', (value, previous) => previous === undefined ? value : `${previous},${value}`)
57
+ .allowExcessArguments(false)
58
+ .action(commandAction(require('../actions/primitivesCheck')))
59
+
33
60
  command.command('keypair')
34
61
  .description('generate or restore a keypair and print JSON')
35
62
  .argument('[privateKey]', 'hex-encoded private key to restore')
@@ -74,11 +74,12 @@ program.command('run')
74
74
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
75
75
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
76
76
  .option('--strict', 'process.exit(1) on any errors', false)
77
+ .option('--profile <name>', 'select an Envfile profile')
77
78
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
78
79
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
79
80
  .option('--token <token>', 'set Armor ⛨ token')
80
81
  .option('--mask [characters]', 'inject masked values, optionally setting visible characters')
81
- .option('--redact', 'redact injected values except public keys (Dotenvspec rules take precedence)', false)
82
+ .option('--redact', 'redact injected values except public keys (Envfile rules take precedence)', false)
82
83
  .option('--lock-password <password>', 'password to unlock private keys (defaults to DOTENVX_LOCK_PASSWORD)')
83
84
  .option('--no-armor', 'disable Dotenvx Armor features')
84
85
  .option('--no-native', 'disable OS secret store features')
@@ -99,6 +100,7 @@ program.command('get')
99
100
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
100
101
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
101
102
  .option('--strict', 'process.exit(1) on any errors', false)
103
+ .option('--profile <name>', 'select an Envfile profile')
102
104
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
103
105
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
104
106
  .option('-a, --all', 'include all machine envs as well')
@@ -122,6 +124,7 @@ program.command('get')
122
124
  program.command('set')
123
125
  .usage('<KEY> [value] [options]')
124
126
  .description('encrypt a single environment variable')
127
+ .option('--profile <name>', 'select an Envfile profile')
125
128
  .addHelpText('after', help.set)
126
129
  .allowUnknownOption()
127
130
  .argument('KEY', 'KEY')
@@ -156,6 +159,7 @@ program.command('del')
156
159
  function configureEncryptCommand (command) {
157
160
  return command
158
161
  .description('encrypt .env file(s)')
162
+ .option('--profile <name>', 'select an Envfile profile')
159
163
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
160
164
  .option('-fk, --env-keys-file <path>', 'path to your .env.keys file (default: same path as your env file)')
161
165
  .option('-k, --key <keys...>', 'keys(s) to encrypt (default: all keys in file)')
@@ -226,9 +230,9 @@ program.command('ls', { hidden: true })
226
230
 
227
231
  // dotenvx spec
228
232
  program.command('spec', { hidden: true })
229
- .description('create a Dotenvspec')
233
+ .description('create an Envfile')
230
234
  .option('--stdout', 'send to stdout')
231
- .option('--overwrite', 'replace existing Dotenvspec, including custom rules, comments, and missing-file blocks')
235
+ .option('--overwrite', 'replace existing Envfile, including custom rules, comments, and missing-file blocks')
232
236
  .option('-f, --env-file <path>', 'file to read variable names from')
233
237
  .action(function () {
234
238
  return commandAction(require('./actions/init')).apply(this, arguments)
@@ -236,11 +240,12 @@ program.command('spec', { hidden: true })
236
240
 
237
241
  // dotenvx check
238
242
  program.command('check', { hidden: true })
239
- .description('check Dotenvspec rules against .env file(s)')
243
+ .description('check Envfile rules against .env file(s)')
240
244
  .option('-e, --env <strings...>', 'environment variable(s) set as string (example: "HELLO=World")', collectEnvs('env'), [])
241
245
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
242
246
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
243
247
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
248
+ .option('--profile <name>', 'select an Envfile profile')
244
249
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
245
250
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
246
251
  .option('--token <token>', 'set Armor ⛨ token')
@@ -336,7 +341,7 @@ function hiddenSubcommands (name) {
336
341
  program.command('hidden')
337
342
  .allowExcessArguments(false)
338
343
  .description('hidden features')
339
- .addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\n protect protect secrets and private keys from code commits\n ls [directory] print all .env files in a tree structure\n genexample [directory] generate .env.example\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nBeta Commands:\n spec create a Dotenvspec\n check check Dotenvspec rules against .env file(s)\n${hiddenSubcommands('primitives')}\n\nDeprecated Commands:\n gitignore deprecated. use [dotenvx protect]\n precommit [directory] deprecated. use [dotenvx protect]\n prebuild [directory] deprecated. use [dotenvx protect --docker]\n\nRun directly: dotenvx <command>`)
344
+ .addHelpText('after', () => `\nHidden Commands:\n update update dotenvx\n feedback [message] send feedback to dotenvx\n protect protect secrets and private keys from code commits\n ls [directory] print all .env files in a tree structure\n genexample [directory] generate .env.example\n lock ⊡ lock private keys with a local passphrase\n native ⌥ move private keys in/out of your OS secret store\n 1password □ move private keys in/out of 1Password\n bitwarden □ move private keys in/out of Bitwarden\n armor ⛨ move private keys in/out of Dotenvx Armor [www.dotenvx.com/armor]\n curl ⛨ call authenticated api Dotenvx Armor [www.dotenvx.com/armor]\n\nBeta Commands:\n spec create an Envfile\n check check Envfile rules against .env file(s)\n${hiddenSubcommands('primitives')}\n\nDeprecated Commands:\n gitignore deprecated. use [dotenvx protect]\n precommit [directory] deprecated. use [dotenvx protect]\n prebuild [directory] deprecated. use [dotenvx protect --docker]\n\nRun directly: dotenvx <command>`)
340
345
  .action(function () { this.outputHelp() })
341
346
 
342
347
  // dotenvx update
@@ -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 => ['Dotenvspec', 'Envspec', 'Dotenvxspec', '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', 'Dotenvspec', 'Envspec', 'Dotenvxspec', '.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
  }
@@ -10,15 +10,15 @@ function declaration (item) {
10
10
  function renderFile (file) {
11
11
  const quote = file.filename.includes('"') ? "'" : '"'
12
12
  if (file.filename.includes(quote) || /[\r\n\0*?[\]{}]/.test(file.filename)) {
13
- throw new Error(`Unsupported Dotenvspec filename: ${file.filename}`)
13
+ throw new Error(`Unsupported Envfile filename: ${file.filename}`)
14
14
  }
15
15
  const lines = [`file ${quote}${file.filename}${quote} do`]
16
16
  lines.push(...file.declarations.map(item => ` ${declaration(item)}`), 'end')
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 '# Dotenvspec (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,27 +1,25 @@
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
- if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Dotenvspec: ${policyPath}`)
12
+ if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Envfile: ${policyPath}`)
13
13
  return null
14
14
  }
15
15
  return schema
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 = process.env.DOTENV_SPEC !== undefined
23
- ? readEnvspec(undefined, [file])
24
- : readPolicy(resolveEnvspecPath(directory), file)
22
+ let schema = readPolicy(resolveEnvfilePath(directory), file)
25
23
  if (!schema) {
26
24
  let root
27
25
  try {
@@ -34,9 +32,9 @@ module.exports = function protectEnvspec (filepath, content) {
34
32
  // Outside a Git working tree, only an adjacent policy can apply.
35
33
  return null
36
34
  }
37
- if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvspecPath(root), file)
35
+ if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvfilePath(root), file)
38
36
  }
39
37
  if (!schema) return null
40
38
 
41
- 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))
42
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 a Dotenvspec or DOTENV_SPEC')
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
  }