@dotenvx/dotenvx 2.31.0 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/README.md +100 -28
  3. package/package.json +3 -3
  4. package/src/cli/actions/check.js +45 -38
  5. package/src/cli/actions/init.js +23 -13
  6. package/src/cli/actions/protectStdin.js +19 -3
  7. package/src/cli/actions/run.js +15 -11
  8. package/src/cli/commands/armor.js +1 -1
  9. package/src/cli/commands/primitives.js +1 -1
  10. package/src/cli/dotenvx.js +8 -7
  11. package/src/lib/custodians/resolveLocalKey.js +68 -0
  12. package/src/lib/{envfile → envspec}/discovery/discoverEnvFiles.js +1 -1
  13. package/src/lib/{envfile → envspec}/discovery/scanSource.js +1 -1
  14. package/src/lib/{envfile/parsing/envfile.peggy → envspec/parsing/envspec.peggy} +17 -10
  15. package/src/lib/{envfile/parsing/envfileParser.js → envspec/parsing/envspecParser.js} +575 -455
  16. package/src/lib/{envfile/parsing/formatEnvfileSyntaxError.js → envspec/parsing/formatEnvspecSyntaxError.js} +1 -1
  17. package/src/lib/{envfile/parsing/readEnvfile.js → envspec/parsing/readEnvspec.js} +38 -27
  18. package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js} +7 -10
  19. package/src/lib/envspec/rendering/previewEnvspec.js +51 -0
  20. package/src/lib/envspec/rendering/renderEnvspec.js +30 -0
  21. package/src/lib/envspec/validation/diagnosticLocation.js +29 -0
  22. package/src/lib/envspec/validation/protectEnvspec.js +39 -0
  23. package/src/lib/envspec/validation/validateEnvspec.js +57 -0
  24. package/src/lib/helpers/errors.js +7 -6
  25. package/src/lib/helpers/isPublicKey.js +3 -0
  26. package/src/lib/helpers/plaintextKeys.js +9 -0
  27. package/src/lib/helpers/redactedValues.js +10 -4
  28. package/src/lib/services/armorPush.js +3 -15
  29. package/src/lib/services/armorUp.js +5 -12
  30. package/src/lib/services/init.js +27 -22
  31. package/src/lib/services/validate.js +20 -10
  32. package/src/lib/transforms/encrypt.js +21 -8
  33. package/src/lib/envfile/rendering/renderEnvfile.js +0 -26
  34. package/src/lib/envfile/validation/validateEnvfile.js +0 -24
  35. /package/src/lib/{envfile → envspec}/discovery/extractEnvKeys.js +0 -0
  36. /package/src/lib/{envfile → envspec}/validation/encryptedSources.js +0 -0
  37. /package/src/lib/{envfile → envspec}/validation/validate.js +0 -0
@@ -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
@@ -0,0 +1,68 @@
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+ const { scan, derive } = require('@dotenvx/primitives')
4
+ const custodians = require('./index')
5
+ const protection = require('./lock')
6
+ const keynames = require('../conventions/keynames')
7
+ const matchesStoredKey = require('../helpers/matchesStoredKey')
8
+ const removeEnvKey = require('../helpers/removeEnvKey')
9
+ const Errors = require('../helpers/errors')
10
+
11
+ function read (filename) {
12
+ try { return fs.readFileSync(filename, 'utf8') } catch (error) {
13
+ if (error.code === 'ENOENT') return undefined
14
+ throw error
15
+ }
16
+ }
17
+
18
+ function value (src, name) {
19
+ return src === undefined ? undefined : scan(src).parsed[name]?.at(-1)
20
+ }
21
+
22
+ // Return the originating store with the key, so a move only removes that source.
23
+ // Never look up Armor itself: these operations upload a locally held private key.
24
+ module.exports = async function resolveLocalKey (envFile = '.env', { allowMissing = false } = {}) {
25
+ const src = read(envFile)
26
+ const { publicKeyName, privateKeyName } = keynames(envFile, src || '')
27
+ let publicKey = value(src, publicKeyName)
28
+ if (allowMissing && !publicKey) {
29
+ if (src === undefined) throw new Errors({ envFilepath: envFile }).missingEnvFile()
30
+ throw new Errors({ key: publicKeyName }).missingKey()
31
+ }
32
+
33
+ async function result (stored, remove, reread) {
34
+ // A file-only push remains supported, including password-locked keys.
35
+ if (!publicKey) publicKey = stored.startsWith('locked:') ? stored.split(':')[1] : derive(stored)
36
+ if (!matchesStoredKey(publicKey, stored)) throw new Error('private key does not match the .env public key')
37
+ const privateKey = (await protection.unlock(publicKey, { [publicKey]: stored }))[publicKey]
38
+ return {
39
+ publicKey,
40
+ privateKey,
41
+ privateKeyName,
42
+ async remove () {
43
+ if (await reread() !== stored) throw new Error('private key changed during upload; original storage was not modified')
44
+ await remove()
45
+ }
46
+ }
47
+ }
48
+
49
+ const files = [...new Set([path.resolve(path.dirname(envFile), '.env.keys'), path.resolve('.env.keys')])]
50
+ for (const filename of files) {
51
+ const stored = value(read(filename), privateKeyName)
52
+ if (stored) return result(stored, () => removeEnvKey(privateKeyName, filename), () => value(read(filename), privateKeyName))
53
+ }
54
+
55
+ if (publicKey) {
56
+ for (const id of ['native', 'onepassword', 'bitwarden']) {
57
+ const custodian = custodians.get(id)
58
+ if (!custodian.enabled() || (custodian.configured && !custodian.configured())) continue
59
+ const stored = (await custodian.get(publicKey))?.[publicKey]
60
+ if (stored) return result(stored, () => custodian.delete(publicKey), async () => (await custodian.get(publicKey))?.[publicKey])
61
+ }
62
+ }
63
+
64
+ // Up can be repeated for a key already held by Armor; the server verifies it.
65
+ if (allowMissing) return { publicKey, privateKeyName, remove: async () => {} }
66
+ if (!publicKey && src === undefined) throw new Errors({ envFilepath: '.env.keys' }).missingEnvFile()
67
+ throw new Error(`private key ${privateKeyName} not found in .env.keys, OS secret storage, 1Password, or Bitwarden`)
68
+ }
@@ -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 }; }