@dotenvx/dotenvx 2.31.1 → 2.32.1

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 (47) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/README.md +100 -28
  3. package/package.json +3 -3
  4. package/src/cli/actions/check.js +45 -38
  5. package/src/cli/actions/encrypt.js +3 -5
  6. package/src/cli/actions/init.js +23 -13
  7. package/src/cli/actions/protectStdin.js +19 -3
  8. package/src/cli/actions/run.js +15 -11
  9. package/src/cli/actions/set.js +2 -4
  10. package/src/cli/commands/primitives.js +1 -1
  11. package/src/cli/dotenvx.js +8 -7
  12. package/src/lib/custodians/managed/armor/index.js +1 -1
  13. package/src/lib/custodians/managed/armor/store.js +11 -3
  14. package/src/lib/{envfile → envspec}/discovery/discoverEnvFiles.js +1 -1
  15. package/src/lib/{envfile → envspec}/discovery/scanSource.js +1 -1
  16. package/src/lib/{envfile/parsing/envfile.peggy → envspec/parsing/envspec.peggy} +17 -10
  17. package/src/lib/{envfile/parsing/envfileParser.js → envspec/parsing/envspecParser.js} +575 -455
  18. package/src/lib/{envfile/parsing/formatEnvfileSyntaxError.js → envspec/parsing/formatEnvspecSyntaxError.js} +1 -1
  19. package/src/lib/{envfile/parsing/readEnvfile.js → envspec/parsing/readEnvspec.js} +38 -27
  20. package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js} +7 -10
  21. package/src/lib/envspec/rendering/previewEnvspec.js +51 -0
  22. package/src/lib/envspec/rendering/renderEnvspec.js +30 -0
  23. package/src/lib/envspec/validation/diagnosticLocation.js +29 -0
  24. package/src/lib/envspec/validation/protectEnvspec.js +39 -0
  25. package/src/lib/envspec/validation/validateEnvspec.js +57 -0
  26. package/src/lib/helpers/custodySelect.js +25 -0
  27. package/src/lib/helpers/errors.js +7 -6
  28. package/src/lib/helpers/isPublicKey.js +3 -0
  29. package/src/lib/helpers/plaintextKeys.js +9 -0
  30. package/src/lib/helpers/prompts.js +7 -1
  31. package/src/lib/helpers/redactedValues.js +10 -4
  32. package/src/lib/helpers/selectKeyStorage.js +62 -17
  33. package/src/lib/helpers/storeKeyStorage.js +19 -0
  34. package/src/lib/services/armorDown.js +1 -0
  35. package/src/lib/services/armorMove.js +1 -0
  36. package/src/lib/services/armorPull.js +1 -0
  37. package/src/lib/services/armorPush.js +1 -0
  38. package/src/lib/services/armorUp.js +1 -0
  39. package/src/lib/services/init.js +27 -22
  40. package/src/lib/services/validate.js +20 -10
  41. package/src/lib/transforms/encrypt.js +28 -14
  42. package/src/lib/transforms/set.js +5 -6
  43. package/src/lib/envfile/rendering/renderEnvfile.js +0 -26
  44. package/src/lib/envfile/validation/validateEnvfile.js +0 -24
  45. /package/src/lib/{envfile → envspec}/discovery/extractEnvKeys.js +0 -0
  46. /package/src/lib/{envfile → envspec}/validation/encryptedSources.js +0 -0
  47. /package/src/lib/{envfile → envspec}/validation/validate.js +0 -0
@@ -52,7 +52,6 @@ async function run () {
52
52
  const options = normalizeDotenvConfigIgnore(normalizeDotenvConfigConvention(normalizeDotenvConfigQuiet(this.opts())))
53
53
  const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
54
54
  const maskEnabled = options.mask !== undefined
55
- const redactEnabled = options.redact === true
56
55
  let showChar = options.mask
57
56
  if (options.mask === true) {
58
57
  showChar = 6
@@ -78,8 +77,6 @@ async function run () {
78
77
  debugOptions = { ...options, env: (options.env || []).map(envSrc => maskEnvSrc(envSrc, showChar)), token }
79
78
  }
80
79
  if (options.lockPassword !== undefined) debugOptions = { ...debugOptions, lockPassword: '[REDACTED]' }
81
- logger.debug(`options: ${JSON.stringify(debugOptions)}`)
82
- logger.debug(`process command [${commandArgs.join(' ')}]`)
83
80
 
84
81
  const ignore = options.ignore || []
85
82
 
@@ -102,7 +99,8 @@ async function run () {
102
99
  const {
103
100
  processedEnvs,
104
101
  readableFilepaths,
105
- hasEnvfile,
102
+ hasEnvspec,
103
+ schema,
106
104
  proxyCredentials,
107
105
  proxyToken,
108
106
  session: sesh,
@@ -112,7 +110,7 @@ async function run () {
112
110
  envs: this.envs,
113
111
  options,
114
112
  processEnv: process.env,
115
- requireEnvfile: false,
113
+ requireEnvspec: false,
116
114
  command: commandArgs,
117
115
  onStatus: (text) => {
118
116
  if (spinner && text) spinner.text = text
@@ -120,10 +118,13 @@ async function run () {
120
118
  })
121
119
  if (proxyError) throw proxyError
122
120
 
123
- if (redactEnabled) {
124
- sensitiveValues = redactedValues(processedEnvs)
121
+ if (hasEnvspec || options.redact === true) {
122
+ sensitiveValues = redactedValues(processedEnvs, schema, process.env, options.redact === true)
125
123
  }
126
124
 
125
+ logger.debug(redactOutput(`options: ${JSON.stringify(debugOptions)}`, sensitiveValues))
126
+ logger.debug(redactOutput(`process command [${commandArgs.join(' ')}]`, sensitiveValues))
127
+
127
128
  if (maskEnabled) {
128
129
  commandEnv = { ...process.env }
129
130
  maskProcessedEnvs(processedEnvs, commandEnv, showChar)
@@ -132,10 +133,10 @@ async function run () {
132
133
  if (error) {
133
134
  if (ignore.includes(error.code)) {
134
135
  logger.verbose(`ignored: ${error.message}`)
135
- } else if (options.strict || hasEnvfile) {
136
+ } else if (options.strict || error.diagnostics?.some(diagnostic => diagnostic.strict)) {
136
137
  throw error
137
138
  } else {
138
- logger.error(error.messageWithHelp || error.message)
139
+ logger.warn(error.messageWithHelp || error.message)
139
140
  }
140
141
  }
141
142
 
@@ -149,7 +150,7 @@ async function run () {
149
150
  if (maskEnabled) {
150
151
  envString = maskEnvSrc(processedEnv.string, showChar)
151
152
  }
152
- logger.verbose(`loading env from string (${envString})`)
153
+ logger.verbose(redactOutput(`loading env from string (${envString})`, sensitiveValues))
153
154
  }
154
155
 
155
156
  for (const error of processedEnv.errors || []) {
@@ -158,7 +159,10 @@ async function run () {
158
159
  continue // ignore error
159
160
  }
160
161
 
161
- if (options.strict) throw error // throw if strict and not ignored
162
+ const strict = processedEnv.type === 'envFile'
163
+ ? (schema.strictByFile?.get(path.resolve(processedEnv.filepath)) ?? schema.strict)
164
+ : schema.strict
165
+ if (options.strict || strict) throw error // throw if strict and not ignored
162
166
 
163
167
  if (error.code === 'MISSING_ENV_FILE' && options.convention) { // do not output error for conventions (too noisy)
164
168
  // intentionally quiet
@@ -7,7 +7,6 @@ const catchAndLog = require('../../lib/helpers/catchAndLog')
7
7
  const createSpinner = require('../../lib/helpers/createSpinner')
8
8
  const Errors = require('../../lib/helpers/errors')
9
9
  const prompts = require('../../lib/helpers/prompts')
10
- const Session = require('../../db/session')
11
10
 
12
11
  async function set (key, value) {
13
12
  const options = this.opts()
@@ -47,7 +46,6 @@ async function set (key, value) {
47
46
  }
48
47
 
49
48
  const spinner = await createSpinner({ ...spinnerOptions, ...options, text: settingMessage })
50
- const sesh = new Session()
51
49
 
52
50
  logger.debug(`key: ${key}`)
53
51
  logger.debug(`value: ${value}`)
@@ -56,7 +54,7 @@ async function set (key, value) {
56
54
  const envs = this.envs || []
57
55
  const fk = options.envKeysFile || '.env.keys'
58
56
  const noCreate = options.create === false
59
- const noArmor = options.armor === false || (!options.token && (await sesh.noArmor()))
57
+ const noArmor = options.armor === false
60
58
  const noNative = options.native === false || options.noNative === true
61
59
 
62
60
  const noBitwarden = options.bitwarden === false || options.noBitwarden === true
@@ -65,7 +63,7 @@ async function set (key, value) {
65
63
  let errorCount = 0
66
64
 
67
65
  try {
68
- const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await setTransform({ envs, key, value, fk, noArmor, noCreate, encrypt, noNative, no1Password, noBitwarden })
66
+ const { keysSrc, processedEnvs, changedFilepaths, unchangedFilepaths } = await setTransform({ envs, key, value, fk, noArmor, token: options.token, noCreate, encrypt, noNative, no1Password, noBitwarden })
69
67
 
70
68
  if (keysSrc) {
71
69
  await fsx.writeKeyFile(fk, keysSrc)
@@ -31,7 +31,7 @@ module.exports = function primitives (command) {
31
31
  .action(function () { this.help() })
32
32
 
33
33
  command.command('keypair')
34
- .description('generate or restore a key pair and print JSON')
34
+ .description('generate or restore a keypair and print JSON')
35
35
  .argument('[privateKey]', 'hex-encoded private key to restore')
36
36
  .option('--stdin', 'read the private key from stdin')
37
37
  .allowExcessArguments(false)
@@ -72,13 +72,13 @@ program.command('run')
72
72
  .option('-e, --env <strings...>', 'environment variable(s) set as string (example: "HELLO=World")', collectEnvs('env'), [])
73
73
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
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
- .option('--redact', 'redact injected values except keys ending in _PLAIN', false)
76
75
  .option('-o, --overload', 'override existing env variables (by default, existing env vars take precedence over .env files)')
77
76
  .option('--strict', 'process.exit(1) on any errors', false)
78
77
  .option('--convention <name>', 'load a .env convention (available conventions: [\'nextjs\', \'flow\'])')
79
78
  .option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
80
79
  .option('--token <token>', 'set Armor ⛨ token')
81
80
  .option('--mask [characters]', 'inject masked values, optionally setting visible characters')
81
+ .option('--redact', 'redact injected values except public keys (Envspec rules take precedence)', false)
82
82
  .option('--lock-password <password>', 'password to unlock private keys (defaults to DOTENVX_LOCK_PASSWORD)')
83
83
  .option('--no-armor', 'disable Dotenvx Armor features')
84
84
  .option('--no-native', 'disable OS secret store features')
@@ -224,9 +224,11 @@ program.command('ls', { hidden: true })
224
224
  return commandAction(require('./actions/ls')).apply(this, args)
225
225
  })
226
226
 
227
- // dotenvx init
228
- program.command('init', { hidden: true })
229
- .description('select .env files to create an Envfile')
227
+ // dotenvx spec
228
+ program.command('spec', { hidden: true })
229
+ .description('create an Envspec')
230
+ .option('--stdout', 'send to stdout')
231
+ .option('--overwrite', 'replace existing Envspec, including custom rules, comments, and missing-file blocks')
230
232
  .option('-f, --env-file <path>', 'file to read variable names from')
231
233
  .action(function () {
232
234
  return commandAction(require('./actions/init')).apply(this, arguments)
@@ -234,8 +236,7 @@ program.command('init', { hidden: true })
234
236
 
235
237
  // dotenvx check
236
238
  program.command('check', { hidden: true })
237
- .description('check .env file(s) against Envfile')
238
- .option('--strict', 'process.exit(1) on any errors, including missing env files', false)
239
+ .description('check Envspec rules against .env file(s)')
239
240
  .option('-e, --env <strings...>', 'environment variable(s) set as string (example: "HELLO=World")', collectEnvs('env'), [])
240
241
  .option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
241
242
  .option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
@@ -335,7 +336,7 @@ function hiddenSubcommands (name) {
335
336
  program.command('hidden')
336
337
  .allowExcessArguments(false)
337
338
  .description('hidden features')
338
- .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 init create an Envfile from .env files and source code\n check check .env file(s) against Envfile\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>`)
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 an Envspec\n check check Envspec 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>`)
339
340
  .action(function () { this.outputHelp() })
340
341
 
341
342
  // dotenvx update
@@ -6,7 +6,7 @@ module.exports = {
6
6
  id: 'armored',
7
7
  name: '⛨ Armor',
8
8
  custody: 'managed',
9
- enabled: (options = {}) => options.noArmor !== true && options.armor !== false,
9
+ enabled: (options = {}) => options.noArmor !== true && options.armor !== false && process.env.DOTENVX_NO_ARMOR !== 'true',
10
10
  available: () => true,
11
11
  async configured (options = {}) {
12
12
  return !!options.token || !await new Session().noArmor()
@@ -4,10 +4,10 @@ const prompts = require('../../../helpers/prompts')
4
4
  const teamChoicesFromMeta = require('../../../helpers/teamChoicesFromMeta')
5
5
  const isTeamRequiredError = require('../../../helpers/isTeamRequiredError')
6
6
 
7
- async function store (publicKey, privateKey) {
7
+ async function store (publicKey, privateKey, context = {}) {
8
8
  const sesh = new Session()
9
9
  const hostname = sesh.hostname()
10
- const token = sesh.token()
10
+ const token = context.token || sesh.token()
11
11
  const devicePublicKey = sesh.devicePublicKey()
12
12
 
13
13
  try {
@@ -23,13 +23,21 @@ async function store (publicKey, privateKey) {
23
23
  if (choices.length > 1) {
24
24
  team = await prompts.select({
25
25
  message: 'Select team',
26
- choices
26
+ prefix: '⛨',
27
+ choices: context.allowCustodyBack ? [...choices, { name: '← back', value: '__back' }] : choices,
28
+ ...(context.allowCustodyBack ? { navigation: true, backValue: '__back' } : {})
27
29
  }, {
28
30
  input: process.stdin,
29
31
  output: process.stderr
30
32
  })
31
33
  }
32
34
 
35
+ if (team === '__back') {
36
+ const error = new Error('Return to private key custody')
37
+ error.code = 'KEY_CUSTODY_BACK'
38
+ throw error
39
+ }
40
+
33
41
  await new PostArmorUp(hostname, token, devicePublicKey, publicKey, privateKey, team).run()
34
42
  }
35
43
  }
@@ -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 => entry.name === 'Envfile' || entry.name === 'package.json')) return
14
+ if (current !== root && entries.some(entry => entry.name === 'Envspec' || entry.name === 'package.json')) 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', '.env.schema'])
7
+ const projectMarkers = new Set(['package.json', 'Envspec', '.env.schema'])
8
8
  const languages = {
9
9
  js: 'js',
10
10
  mjs: 'js',
@@ -1,29 +1,35 @@
1
1
  Document
2
- = _ encrypted:EncryptedDefault? _ entries:((FileBlock / Declaration) _)* {
3
- return { encrypted: encrypted === true, declarations: entries.map(item => item[0]).filter(item => !item.file), files: entries.map(item => item[0]).filter(item => item.file) };
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 Envspec setting: strict");
6
+ return { ...settings[0], declarations: items.filter(item => item.name), files: items.filter(item => item.file) };
4
7
  }
5
8
 
6
9
  FileBlock
7
- = "file" [ \t]+ file:Filename [ \t]+ "do" [ \t]* Comment? Newline _ encrypted:EncryptedDefault? _ declarations:(Declaration _)* "end" [ \t]* Comment? (Newline / !.) {
8
- return { file, encrypted, declarations: declarations.map(item => item[0]) };
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 Envspec setting: strict");
14
+ return { file, ...settings[0], declarations: items.filter(item => item.name) };
9
15
  }
10
16
 
17
+ Strict
18
+ = "strict" [ \t]+ value:Boolean [ \t]* Comment? (Newline / !.) { return { strict: value }; }
19
+
11
20
  Filename "a quoted filename"
12
21
  = '"' value:$([^"\r\n\0]+) '"' { return value; }
13
22
  / "'" value:$([^'\r\n\0]+) "'" { return value; }
14
23
 
15
- EncryptedDefault
16
- = "encrypted" [ \t]+ value:Boolean [ \t]* Comment? (Newline / !.) { return value; }
17
-
18
24
  Declaration
19
25
  = "env" [ \t]+ name:Name options:Option* [ \t]* Comment? (Newline / !.) {
20
26
  const declaration = { name };
21
27
  const seen = new Set();
22
28
  for (const option of options) {
23
- if (seen.has(option.key)) error(`Duplicate Envfile option: ${option.key}`);
29
+ if (seen.has(option.key)) error(`Duplicate Envspec option: ${option.key}`);
24
30
  if ((option.key === "optional" && seen.has("required")) ||
25
31
  (option.key === "required" && seen.has("optional"))) {
26
- error("Cannot combine required and optional in an Envfile declaration");
32
+ error("Cannot combine required and optional in an Envspec declaration");
27
33
  }
28
34
  seen.add(option.key);
29
35
  if (option.key === "optional") declaration.required = !option.value;
@@ -36,7 +42,8 @@ Option
36
42
  = [ \t]* "," _ "proxy" [ \t]* ":" _ value:(ProxyOptions / Disabled) { return { key: "proxy", value }; }
37
43
  / [ \t]* "," _ "required" [ \t]* ":" _ value:Boolean { return { key: "required", value }; }
38
44
  / [ \t]* "," _ "optional" [ \t]* ":" _ value:Boolean { return { key: "optional", value }; }
39
- / [ \t]* "," _ "encrypted" [ \t]* ":" _ value:Boolean { return { key: "encrypted", value }; }
45
+ / [ \t]* "," _ ("redacted" / "redact") [ \t]* ":" _ value:Boolean { return { key: "redacted", value }; }
46
+ / [ \t]* "," _ ("encrypted" / "encrypt") [ \t]* ":" _ value:Boolean { return { key: "encrypted", value }; }
40
47
  / [ \t]* "," _ "type" [ \t]* ":" _ value:Type { return { key: "type", value }; }
41
48
  / [ \t]* "," _ "enum" [ \t]* ":" _ value:Enum { return { key: "enum", value }; }
42
49
  / [ \t]* "," _ key:("min" / "max") [ \t]* ":" _ value:Integer { return { key, value }; }