@dotenvx/dotenvx 2.31.1 → 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 (33) hide show
  1. package/CHANGELOG.md +12 -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/primitives.js +1 -1
  9. package/src/cli/dotenvx.js +8 -7
  10. package/src/lib/{envfile → envspec}/discovery/discoverEnvFiles.js +1 -1
  11. package/src/lib/{envfile → envspec}/discovery/scanSource.js +1 -1
  12. package/src/lib/{envfile/parsing/envfile.peggy → envspec/parsing/envspec.peggy} +17 -10
  13. package/src/lib/{envfile/parsing/envfileParser.js → envspec/parsing/envspecParser.js} +575 -455
  14. package/src/lib/{envfile/parsing/formatEnvfileSyntaxError.js → envspec/parsing/formatEnvspecSyntaxError.js} +1 -1
  15. package/src/lib/{envfile/parsing/readEnvfile.js → envspec/parsing/readEnvspec.js} +38 -27
  16. package/src/lib/{envfile/rendering/normalizeEnvfile.js → envspec/rendering/normalizeEnvspec.js} +7 -10
  17. package/src/lib/envspec/rendering/previewEnvspec.js +51 -0
  18. package/src/lib/envspec/rendering/renderEnvspec.js +30 -0
  19. package/src/lib/envspec/validation/diagnosticLocation.js +29 -0
  20. package/src/lib/envspec/validation/protectEnvspec.js +39 -0
  21. package/src/lib/envspec/validation/validateEnvspec.js +57 -0
  22. package/src/lib/helpers/errors.js +7 -6
  23. package/src/lib/helpers/isPublicKey.js +3 -0
  24. package/src/lib/helpers/plaintextKeys.js +9 -0
  25. package/src/lib/helpers/redactedValues.js +10 -4
  26. package/src/lib/services/init.js +27 -22
  27. package/src/lib/services/validate.js +20 -10
  28. package/src/lib/transforms/encrypt.js +21 -8
  29. package/src/lib/envfile/rendering/renderEnvfile.js +0 -26
  30. package/src/lib/envfile/validation/validateEnvfile.js +0 -24
  31. /package/src/lib/{envfile → envspec}/discovery/extractEnvKeys.js +0 -0
  32. /package/src/lib/{envfile → envspec}/validation/encryptedSources.js +0 -0
  33. /package/src/lib/{envfile → envspec}/validation/validate.js +0 -0
package/CHANGELOG.md CHANGED
@@ -2,7 +2,18 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
- [Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.31.1...main)
5
+ [Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.32.0...main)
6
+
7
+ ## [2.32.0](https://github.com/dotenvx/dotenvx/compare/v2.31.1...v2.32.0) (2026-09-29)
8
+
9
+ ### Changed
10
+
11
+ * BREAKING: `Envfile` renamed to `Envspec` file ([#996](https://github.com/dotenvx/dotenvx/pull/996))
12
+ * BREAKING: `dotenvx init` removed. renamed to `dotenvx spec`. ([#996](https://github.com/dotenvx/dotenvx/pull/996))
13
+
14
+ ### Added
15
+
16
+ * Envspec rules now guide check, run, encrypt, and protect. ([#996](https://github.com/dotenvx/dotenvx/pull/996))
6
17
 
7
18
  ## [2.31.1](https://github.com/dotenvx/dotenvx/compare/v2.31.0...v2.31.1) (2026-09-27)
8
19
 
package/README.md CHANGED
@@ -183,7 +183,8 @@ $ claude --version
183
183
  ```sh
184
184
  $ echo "HELLO=World" > .env
185
185
 
186
- $ dotenvx run --redact -- claude -p 'Run `dotenvx get HELLO` and echo back just Hello VALUE' --dangerously-skip-permissions
186
+ $ dotenvx spec
187
+ $ dotenvx run -- claude -p 'Run `dotenvx get HELLO` and echo back just Hello VALUE' --dangerously-skip-permissions
187
188
  Hello [REDACTED]
188
189
  ```
189
190
 
@@ -204,7 +205,8 @@ $ codex --version
204
205
  ```sh
205
206
  $ echo "HELLO=World" > .env
206
207
 
207
- $ dotenvx run --redact -- codex exec 'Run `dotenvx get HELLO` and echo back just Hello VALUE' --skip-git-repo-check
208
+ $ dotenvx spec
209
+ $ dotenvx run -- codex exec 'Run `dotenvx get HELLO` and echo back just Hello VALUE' --skip-git-repo-check
208
210
  Hello [REDACTED]
209
211
  ```
210
212
 
@@ -225,7 +227,8 @@ $ agent --version
225
227
  ```sh
226
228
  $ echo "HELLO=World" > .env
227
229
 
228
- $ dotenvx run --redact -- agent -p --force 'Run `dotenvx get HELLO` and echo back just Hello VALUE' --output-format text
230
+ $ dotenvx spec
231
+ $ dotenvx run -- agent -p --force 'Run `dotenvx get HELLO` and echo back just Hello VALUE' --output-format text
229
232
  Hello [REDACTED]
230
233
  ```
231
234
 
@@ -1302,67 +1305,74 @@ Hello String
1302
1305
  ```
1303
1306
 
1304
1307
  </details>
1305
- <details><summary>`run --redact`</summary><br>
1308
+ <details><summary>`run with Envspec redaction`</summary><br>
1306
1309
 
1307
- Run any command with real environment variables while automatically redacting their values from stdout and stderr. Keys ending in `_PLAIN` are left visible.
1310
+ Run any command with real environment variables while automatically redacting values selected by your Envspec from stdout and stderr.
1308
1311
 
1309
1312
  ```sh
1310
1313
  $ echo "SECRET=super-secret-value" > .env
1311
- $ echo "VISIBLE_PLAIN=visible-value" >> .env
1312
- $ echo "console.log(process.env.SECRET, process.env.VISIBLE_PLAIN)" > index.js
1314
+ $ echo "PUBLIC_VALUE=visible-value" >> .env
1315
+ $ echo "console.log(process.env.SECRET, process.env.PUBLIC_VALUE)" > index.js
1313
1316
 
1314
- $ dotenvx run --redact --quiet -- node index.js
1317
+ $ dotenvx spec
1318
+ $ dotenvx run --quiet -- node index.js
1315
1319
  [REDACTED] visible-value
1316
1320
  ```
1317
1321
 
1318
- Redaction is off by default. It applies to every key declared in `.env` files and `--env` flags unless the key ends in `_PLAIN`. If an existing environment variable takes precedence, its effective value is redacted too. Matching is exact, so transformed or derived values are not redacted.
1322
+ With an Envspec, all values are redacted by default. Use `redacted: false` on individual declarations to leave those values visible. `spec` generates these settings, including public-name exceptions. If an existing environment variable takes precedence, its effective value follows the same rules. Matching is exact, so transformed or derived values are not redacted.
1323
+
1324
+ Without an Envspec, `dotenvx run --redact -- yourcommand` redacts loaded values except recognized public names (containing `PUBLIC` or starting with `VITE`, case-sensitive). `_PLAIN` values are redacted too. Without either an Envspec or `--redact`, output is not redacted. An Envspec always takes precedence: its rules apply automatically, even when `--redact` is passed.
1319
1325
 
1320
1326
  When stdin, stdout, and stderr are attached to a terminal, dotenvx preserves interactive behavior on macOS and Linux systems with `script` available. Piped and redirected commands continue to use normal stdin, stdout, and stderr streams.
1321
1327
 
1322
1328
  </details>
1323
- <details><summary>`run --redact -- claude -p`</summary><br>
1329
+ <details><summary>`run -- claude -p`</summary><br>
1324
1330
 
1325
1331
  Run Claude in print mode with real environment variables while redacting any values it prints.
1326
1332
 
1327
1333
  ```sh
1328
1334
  $ echo "SECRET=super-secret-value" > .env
1329
1335
 
1330
- $ dotenvx run --redact --quiet -- claude -p 'Print the value of $SECRET'
1336
+ $ dotenvx spec
1337
+ $ dotenvx run --quiet -- claude -p 'Print the value of $SECRET'
1331
1338
  [REDACTED]
1332
1339
  ```
1333
1340
 
1334
1341
  </details>
1335
- <details><summary>`run --redact -- claude`</summary><br>
1342
+ <details><summary>`run -- claude`</summary><br>
1336
1343
 
1337
1344
  Start a fully interactive Claude session. Claude receives the real values, but any values it prints are redacted.
1338
1345
 
1339
1346
  ```sh
1340
1347
  $ echo "SECRET=super-secret-value" > .env
1341
1348
 
1342
- $ dotenvx run --redact --quiet -- claude
1349
+ $ dotenvx spec
1350
+ $ dotenvx run --quiet -- claude
1343
1351
  ```
1344
1352
 
1345
1353
  </details>
1346
- <details><summary>`run --redact -- codex exec`</summary><br>
1354
+ <details><summary>`run -- codex exec`</summary><br>
1347
1355
 
1348
1356
  Run Codex non-interactively with real environment variables while redacting any values it prints.
1349
1357
 
1350
1358
  ```sh
1351
1359
  $ echo "SECRET=super-secret-value" > .env
1352
1360
 
1353
- $ dotenvx run --redact --quiet -- codex exec 'Print the value of $SECRET'
1361
+ $ dotenvx spec
1362
+ $ dotenvx run --quiet -- codex exec 'Print the value of $SECRET'
1354
1363
  [REDACTED]
1355
1364
  ```
1356
1365
 
1357
1366
  </details>
1358
- <details><summary>`run --redact -- codex`</summary><br>
1367
+ <details><summary>`run -- codex`</summary><br>
1359
1368
 
1360
1369
  Start a fully interactive Codex session. Codex receives the real values, but any values it prints are redacted.
1361
1370
 
1362
1371
  ```sh
1363
1372
  $ echo "SECRET=super-secret-value" > .env
1364
1373
 
1365
- $ dotenvx run --redact --quiet -- codex
1374
+ $ dotenvx spec
1375
+ $ dotenvx run --quiet -- codex
1366
1376
  ```
1367
1377
 
1368
1378
  </details>
@@ -1557,12 +1567,12 @@ Hello production
1557
1567
  Available log levels are `error, warn, info, verbose, debug, silly` ([source](https://docs.npmjs.com/cli/v8/using-npm/logging#setting-log-levels))
1558
1568
 
1559
1569
  </details>
1560
- <details><summary>`run with an Envfile`</summary><br>
1570
+ <details><summary>`run with an Envspec`</summary><br>
1561
1571
 
1562
- When an `Envfile` is present, `run` automatically validates the resolved environment before starting your command. No validation flag is needed.
1572
+ When an `Envspec` is present, `run` and `check` validate the same requirements: required values, types, enums, ranges, and storage encryption. No validation flag is needed. `run` performs validation before starting your command.
1563
1573
 
1564
1574
  ```ruby
1565
- # Envfile
1575
+ # Envspec
1566
1576
  env "DATABASE_URL", type: "url"
1567
1577
  env "API_KEY"
1568
1578
  env "SENTRY_DSN", optional: true
@@ -1573,10 +1583,30 @@ $ dotenvx run -- node index.js
1573
1583
  [INVALID_ENV] DATABASE_URL is required; API_KEY is required
1574
1584
  ```
1575
1585
 
1576
- Envfile validation failures stop the command. Other loading errors require `--strict` to stop execution.
1586
+ Envspec validation failures, including unencrypted values, warn by default; `run --strict` stops before launching the command. A `strict true` setting in Envspec, at the root or in an active file block, also makes its validation failures fatal. `check` always exits with failure when validation fails. Strictness changes enforcement, not which rules are checked. Invalid Envspec syntax always stops execution.
1587
+
1588
+ Envspec values default to `redacted: true`: `run` masks their values in child stdout/stderr and resolved-value debug output, while the child still receives the real values. Set `redacted: false` for values that may appear in output. This is independent of `encrypted: true`, which requires an encrypted source.
1589
+
1590
+ ```ruby
1591
+ file ".env.development" do
1592
+ env "BASE_URL", type: "url", redacted: false
1593
+ env "TOKEN_SECRET", encrypted: true
1594
+ end
1595
+ ```
1596
+
1597
+ `spec` generates declarations with encryption and redaction required by default. Encryption is required by default: root and file-level `encrypted` settings are not supported. Use `encrypted: false` on individual declarations to permit plaintext. Entirely plaintext inputs generate no encryption exceptions except for keys ending in `_PLAIN`, so the next `encrypt` encrypts the remaining values. `_PLAIN` keys get `encrypted: false` only when none of their assignments contain ciphertext; code-only references do not infer this exception. For files that already contain ciphertext, `spec` preserves plaintext values with per-key exceptions. Source files are never modified.
1598
+
1599
+ `spec` infers `redacted: false` for names starting with `PUBLIC`, `VITE`, `NEXT_PUBLIC`, or `NUXT_PUBLIC`, or containing `PUBLIC` anywhere (case-sensitive). This affects visibility only; public names still require encryption unless explicitly exempted. Other names, including those ending in `_PLAIN`, remain redacted.
1600
+
1601
+ If an Envspec already exists, `spec` leaves it untouched and prints `○ Envspec already exists [edit or run: spec --overwrite]`. Use `spec --overwrite` to regenerate it from the selected inputs, replacing custom rules, comments, and blocks for files absent from this machine. Interactive overwrite runs show the full file-and-code checklist with the prompt `Recreate Envspec from .env files and code`. Noninteractive runs use `.env.example` and `.env`, or the file selected with `-f`. Input validation finishes before the old Envspec is replaced; cancelled selection leaves it untouched. Symlinked Envspecs cannot be overwritten.
1602
+
1603
+ Use `dotenvx spec --stdout` to print the generated Envspec without writing it, or `dotenvx spec --stdout -f .env.production` to select an input file. This works even when an Envspec already exists; `--stdout` leaves it untouched even with `--overwrite`. Prompts and progress stay on stderr so stdout contains only the generated content.
1604
+
1605
+ Root and file-level `redacted` settings are not supported. Use per-key `redacted: false` to permit output visibility. When selected file policies disagree about a variable, redaction wins. `check` shows individual issues or a compact success summary without displaying values.
1606
+
1577
1607
 
1578
1608
  </details>
1579
- <details><summary>`run with Envfile file rules`</summary><br>
1609
+ <details><summary>`run with Envspec file rules`</summary><br>
1580
1610
 
1581
1611
  Use exact file blocks to override rules for selected files:
1582
1612
 
@@ -1586,7 +1616,6 @@ env "PORT", type: "port"
1586
1616
  env "STRIPE_SECRET_KEY", optional: true
1587
1617
 
1588
1618
  file ".env.production" do
1589
- encrypted true
1590
1619
  env "STRIPE_SECRET_KEY", required: true
1591
1620
  env "PORT", min: 1024
1592
1621
  end
@@ -1594,10 +1623,51 @@ end
1594
1623
 
1595
1624
  Both `dotenvx run -f .env.production -- node index.js` and `dotenvx check -f .env.production` use the production rules. Block declarations inherit top-level options and override only the options they specify. A block's `encrypted` directive applies to all inherited and newly declared variables; a per-variable `encrypted:` option inside that block overrides it.
1596
1625
 
1597
- Paths in file blocks are relative to the Envfile. They match the selected paths exactly after path normalization (`./.env.production` matches `.env.production`); they are not basename matches or globs. Directory inputs and `DOTENV_FILE` use their resolved file paths.
1626
+ Paths in file blocks are relative to the Envspec. They match the selected paths exactly after path normalization (`./.env.production` matches `.env.production`); they are not basename matches or globs. Directory inputs and `DOTENV_FILE` use their resolved file paths.
1598
1627
 
1599
1628
  When no file block matches, top-level rules apply. When one or more blocks match, each matching block's inherited rules must hold for the final resolved environment. Shell values, fallback files, and `--overload` cannot bypass them. A selected missing file still activates its block. Multiple matching blocks cannot cancel each other's restrictions; conflicting proxy domains are rejected. Blocks cannot be nested, and duplicate declarations within one scope or duplicate file blocks are errors.
1600
1629
 
1630
+ </details>
1631
+ <details><summary>`check`</summary><br>
1632
+
1633
+ Validate the final resolved environment against your Envspec, using the same loader and precedence as `run`:
1634
+
1635
+ ```sh
1636
+ $ dotenvx check -f .env.local -f .env
1637
+ ▣ valid (.env.local, .env)
1638
+
1639
+ $ dotenvx check -f .env.production
1640
+ ☠ TOKEN_SECRET not encrypted (.env.production:4)
1641
+ ```
1642
+
1643
+ Envspec `file` blocks define policy; they do not select files to load. By default, `check` uses the same `.env` selection as `run`, including configured paths and private-key-based filename inference. Use repeated `-f` flags or `--convention` to select layers. `DOTENV_FILE` and its aliases are also supported.
1644
+
1645
+ All selected sources are merged before validation. The first file wins by default, existing shell values take precedence, and `--overload` lets later sources override earlier values. Partial files can satisfy the schema together. Encryption requirements apply to the source of the winning value, not to every overridden assignment on disk. Each selected file block's inherited rules must hold for the final environment, just as with `run`.
1646
+
1647
+ Missing files explicitly selected with `-f` or `DOTENV_FILE` (and its aliases) fail the check. Missing optional convention layers and implicit default files are reported as `○ skipped (filename)`. `check` has no `--strict` flag. Required values must still resolve; shell or inline values can satisfy the schema without a local file. A check with no readable files, inline values, or declared shell values fails rather than reporting an empty success.
1648
+
1649
+ On interactive terminals, a single progress line updates with the key being checked. CI and redirected output have no animation. All check output goes to stderr. Success names the loaded sources; validation failures use one diagnostic per issue with the winning source location where available. Shell and inline overrides are identified separately. Failed checks exit with code 1.
1650
+
1651
+ </details>
1652
+ <details><summary>`protect with an Envspec`</summary><br>
1653
+
1654
+ The Git protection filter reads `Envspec` in the same directory as the file being staged. Encryption is required by default. Keys explicitly marked `encrypted: false` may be committed as plaintext:
1655
+
1656
+ ```ruby
1657
+ env "BASE_URL", encrypted: false
1658
+ env "TOKEN_SECRET"
1659
+ ```
1660
+
1661
+ This permits plaintext `BASE_URL` while requiring `TOKEN_SECRET` and undeclared keys to be encrypted. Only keys explicitly marked `encrypted: false` may remain plaintext. `redacted` only controls output visibility.
1662
+
1663
+ Without an Envspec, protection keeps its existing rules, including exemptions for `.env.example`, `.env.vault`, and `.env.x`. A `_PLAIN` suffix alone does not permit plaintext through Git protection.
1664
+
1665
+ Protection inspects every assignment in the incoming Git blob, including duplicates. It does not merge files, use shell overrides, or decrypt values. Empty values, public encryption keys, and `op://` / `bw://` references remain allowed. Private-key files (`.env.keys*`) and nonempty plaintext `DOTENV_PRIVATE_KEY` values remain blocked even with `encrypted: false`.
1666
+
1667
+ The policy is read from the working-tree Envspec beside the staged file, even if that policy itself is unstaged. Parent directories are not searched. Invalid or unreadable policies block staging with an error. Envspec encryption rules also apply to otherwise exempt files such as `.env.example`.
1668
+
1669
+ Accepted blobs pass through byte-for-byte. This integration applies to Git protection, not `protect --docker`.
1670
+
1601
1671
  </details>
1602
1672
  <details><summary>`run --strict`</summary><br>
1603
1673
 
@@ -2202,7 +2272,7 @@ $ dotenvx set HELLO_PLAIN World
2202
2272
  set HELLO_PLAIN (.env)
2203
2273
  ```
2204
2274
 
2205
- Keys ending in `_PLAIN` are not encrypted by `dotenvx set` or `dotenvx encrypt`.
2275
+ Keys ending in `_PLAIN` are not encrypted by `dotenvx set`. `dotenvx encrypt` also skips these keys when there is no Envspec; with an Envspec, its encryption rules take precedence.
2206
2276
 
2207
2277
  </details>
2208
2278
  <details><summary>`set KEY value --no-native`</summary><br>
@@ -2261,6 +2331,8 @@ $ dotenvx del HELLO -f .env.production
2261
2331
 
2262
2332
  Encrypt the contents of a `.env` file to an encrypted `.env` file.
2263
2333
 
2334
+ When the current directory contains an Envspec, `encrypt` encrypts all keys except those explicitly marked `encrypted: false` in the applicable declarations. Values with effective `encrypted: false` remain unchanged, including any existing ciphertext. Undeclared keys require encryption too; both `run` and `check` validate loaded keys and their shell overrides without checking unrelated host environment variables. `run` warns on validation failures by default and refuses to launch when strictness is enabled; `check` exits with failure. The policy applies even with `--key` or `--stdout`; `--exclude-key` can further narrow the selection. If no values need encryption, no keypair is generated. Invalid Envspecs fail rather than falling back to encrypting everything. The Envspec itself is never modified.
2335
+
2264
2336
  ```sh
2265
2337
  $ echo "HELLO=World" > .env
2266
2338
 
@@ -3214,7 +3286,7 @@ INVALID_PUBLIC_KEY= # a public key is malformed or otherwise invalid
3214
3286
  MALFORMED_ENCRYPTED_DATA= # the encrypted value is malformed
3215
3287
  MISPAIRED_PRIVATE_KEY= # a private key does not match the existing public key
3216
3288
  MISSING_DIRECTORY= # the requested directory does not exist
3217
- ENVFILE_REQUIRED= # the required Envfile does not exist
3289
+ ENVSPEC_REQUIRED= # the required Envspec does not exist
3218
3290
  MISSING_ENV_FILE= # a requested environment file does not exist
3219
3291
  MISSING_ENV_FILES= # no .env* files were found
3220
3292
  MISSING_ENV_KEYS_FILE= # the requested .env.keys file does not exist
@@ -3226,8 +3298,8 @@ MISSING_REQUIRED= # validation detail for which required variables are missing;
3226
3298
  MISSING_VALUE= # no value was supplied for a key
3227
3299
  NOT_FOUND= # a private key was not found in the native secret store
3228
3300
  PRECOMMIT_HOOK_MODIFY_FAILED= # dotenvx could not update the pre-commit hook
3229
- INVALID_ENV= # resolved values do not satisfy Envfile rules
3230
- MALFORMED_ENVFILE= # Envfile syntax or configuration is invalid
3301
+ INVALID_ENV= # resolved values do not satisfy Envspec rules
3302
+ MALFORMED_ENVSPEC= # Envspec syntax or configuration is invalid
3231
3303
  WRONG_PRIVATE_KEY= # the supplied private key cannot decrypt the value
3232
3304
  ```
3233
3305
 
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.31.1",
2
+ "version": "2.32.0",
3
3
  "name": "@dotenvx/dotenvx",
4
4
  "description": "a secure dotenv–from the creator of `dotenv`",
5
5
  "author": "@motdotla",
@@ -50,7 +50,7 @@
50
50
  "release:check": "npm test && npm run testshell",
51
51
  "prerelease": "npm run release:check",
52
52
  "release": "npm run release:check && standard-version",
53
- "build:envfile": "peggy --format commonjs -o src/lib/envfile/parsing/envfileParser.js src/lib/envfile/parsing/envfile.peggy"
53
+ "build:envspec": "peggy --format commonjs -o src/lib/envspec/parsing/envspecParser.js src/lib/envspec/parsing/envspec.peggy"
54
54
  },
55
55
  "funding": "https://dotenvx.com",
56
56
  "dependencies": {
@@ -82,7 +82,7 @@
82
82
  },
83
83
  "standard": {
84
84
  "ignore": [
85
- "src/lib/envfile/parsing/envfileParser.js"
85
+ "src/lib/envspec/parsing/envspecParser.js"
86
86
  ]
87
87
  }
88
88
  }
@@ -1,72 +1,79 @@
1
1
  const { logger } = require('./../../shared/logger')
2
-
3
2
  const catchAndLog = require('./../../lib/helpers/catchAndLog')
4
3
  const createSpinner = require('../../lib/helpers/createSpinner')
5
4
  const prepareValidatedEnv = require('../../lib/services/validate')
5
+ const diagnosticLocations = require('../../lib/envspec/validation/diagnosticLocation')
6
6
  const normalizeDotenvConfigQuiet = require('../../lib/helpers/normalizeDotenvConfigQuiet')
7
7
  const normalizeDotenvConfigConvention = require('../../lib/helpers/normalizeDotenvConfigConvention')
8
8
  const normalizeDotenvConfigIgnore = require('../../lib/helpers/normalizeDotenvConfigIgnore')
9
+ const path = require('node:path')
10
+ const previewEnvspec = require('../../lib/envspec/rendering/previewEnvspec')
9
11
 
10
12
  async function check () {
11
13
  const options = normalizeDotenvConfigIgnore(normalizeDotenvConfigConvention(normalizeDotenvConfigQuiet(this.opts())))
12
14
  const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
13
- const spinner = await createSpinner({ ...spinnerOptions, ...options, text: 'checking' })
15
+ const spinner = await createSpinner({ ...spinnerOptions, ...options, text: 'checking', ...(process.env.CI ? { spinner: false } : {}) })
14
16
  const ignore = options.ignore || []
17
+ const showPreview = !options.quiet && !['error', 'infoerror', 'warn'].includes(logger.level)
15
18
  let errorCount = 0
16
-
17
- logger.debug(`options: ${JSON.stringify(options)}`)
19
+ const checked = []
20
+ const messages = []
21
+ const report = (level, message) => messages.push({ level, message })
22
+ const flush = () => {
23
+ if (spinner) spinner.stop()
24
+ for (const { level, message } of messages.splice(0)) logger[level](message)
25
+ }
18
26
 
19
27
  try {
20
- const { processedEnvs, readableFilepaths, proxyError, validationError } = await prepareValidatedEnv({
28
+ const { processedEnvs, readableFilepaths, requiredFilepaths, proxyError, validationError, schema, processEnv, proxyCredentials } = await prepareValidatedEnv({
21
29
  envs: this.envs,
22
30
  options,
23
- onStatus: (text) => {
24
- if (spinner && text) spinner.text = text
25
- }
31
+ onStatus: text => { if (spinner && text) spinner.text = text },
32
+ onKey: key => { if (spinner) spinner.text = `checking ${key}` }
26
33
  })
27
-
28
- const sources = [...readableFilepaths]
29
- if (processedEnvs.some(env => env.type === 'env' && env.parsed)) sources.push('--env')
30
- if (sources.length === 0) sources.push('shell environment')
31
- const sourceSummary = `(${sources.join(', ')})`
32
-
33
- for (const processedEnv of processedEnvs) {
34
- for (const error of processedEnv.errors || []) {
35
- if (ignore.includes(error.code)) {
36
- logger.verbose(`ignored: ${error.message}`)
34
+ checked.push(...readableFilepaths)
35
+ if (processedEnvs.some(row => row.type === 'env' && Object.keys(row.parsed || {}).length)) checked.push('--env')
36
+ if (checked.length === 0 && [...schema.redactionRules.keys()].some(key => processEnv[key] !== undefined)) checked.push('shell environment')
37
+ const location = diagnosticLocations(processedEnvs, checked.join(', ') || 'Envspec')
38
+ for (const row of processedEnvs) {
39
+ for (const error of row.errors || []) {
40
+ if (ignore.includes(error.code)) continue
41
+ if (error.code === 'MISSING_ENV_FILE' && !requiredFilepaths.has(path.resolve(row.filepath))) {
42
+ report('infoerror', `○ skipped (${row.filepath})`)
37
43
  continue
38
44
  }
39
-
40
- if (error.code !== 'MISSING_ENV_FILE' || options.strict) errorCount += 1
41
- if (error.code === 'MISSING_ENV_FILE' && options.convention && !options.strict) continue
42
- logger.error(error.messageWithHelp || error.message)
45
+ errorCount++
46
+ report('error', error.messageWithHelp || error.message)
43
47
  }
44
48
  }
45
-
46
49
  if (proxyError) {
47
- proxyError.message += ` ${sourceSummary}`
48
- throw proxyError
50
+ errorCount++
51
+ report('error', proxyError.message)
49
52
  }
50
-
51
- if (validationError) {
52
- const message = `${validationError.message} ${sourceSummary}`
53
- if (ignore.includes(validationError.code)) {
54
- logger.verbose(`ignored: ${message}`)
55
- } else {
56
- errorCount += 1
57
- logger.error(message)
53
+ if (validationError && !ignore.includes(validationError.code)) {
54
+ errorCount++
55
+ for (const diagnostic of showPreview ? [] : validationError.diagnostics) {
56
+ const message = diagnostic.message.replace(`${diagnostic.key} is `, `${diagnostic.key} `)
57
+ report('error', `${message} (${location(diagnostic.key)})`)
58
58
  }
59
59
  }
60
60
 
61
61
  if (spinner) spinner.stop()
62
-
63
- if (errorCount > 0) {
62
+ if (showPreview) {
63
+ const diagnostics = validationError && !ignore.includes(validationError.code) ? validationError.diagnostics : []
64
+ const preview = previewEnvspec(processedEnvs, schema, processEnv, proxyCredentials, diagnostics)
65
+ if (preview) {
66
+ for (const line of preview.split('\n')) logger.info(line)
67
+ }
68
+ }
69
+ flush()
70
+ if (checked.length === 0) {
71
+ logger.error('no environment sources found to check')
64
72
  return { exitCode: 1 }
65
- } else {
66
- logger.success(`▣ valid ${sourceSummary}`)
67
73
  }
74
+ if (errorCount > 0) return { exitCode: 1 }
68
75
  } catch (error) {
69
- if (spinner) spinner.stop()
76
+ flush()
70
77
  catchAndLog(error)
71
78
  return { exitCode: 1, error }
72
79
  }
@@ -1,23 +1,28 @@
1
1
  const fs = require('node:fs')
2
2
  const process = require('node:process')
3
3
  const prompts = require('../../lib/helpers/prompts')
4
- const initEnvfile = require('../../lib/services/init')
5
- const scanSource = require('../../lib/envfile/discovery/scanSource')
6
- const discoverEnvFiles = require('../../lib/envfile/discovery/discoverEnvFiles')
4
+ const initEnvspec = require('../../lib/services/init')
5
+ const scanSource = require('../../lib/envspec/discovery/scanSource')
6
+ const discoverEnvFiles = require('../../lib/envspec/discovery/discoverEnvFiles')
7
7
  const createSpinner = require('../../lib/helpers/createSpinner')
8
8
  const { logger } = require('../../shared/logger')
9
9
  const catchAndLog = require('../../lib/helpers/catchAndLog')
10
10
 
11
- module.exports = async function init () {
12
- const envFile = this.opts().envFile
11
+ module.exports = async function spec () {
12
+ const options = this.opts()
13
+ const envFile = options.envFile
14
+ const overwrite = options.overwrite === true
15
+ const stdout = options.stdout === true
13
16
  const interactive = !process.env.CI && process.stdin.isTTY && process.stderr.isTTY
14
17
  let spinner
15
18
 
16
19
  try {
17
- if (fs.lstatSync('Envfile', { throwIfNoEntry: false })) {
18
- logger.info('○ Envfile already exists (unchanged)')
20
+ const existing = stdout ? undefined : fs.lstatSync('Envspec', { throwIfNoEntry: false })
21
+ if (existing && !overwrite) {
22
+ logger.info('○ Envspec already exists [edit or run: spec --overwrite]')
19
23
  return
20
24
  }
25
+ if (existing && !existing.isFile()) throw new Error('Cannot replace Envspec: expected a regular file')
21
26
 
22
27
  let envFiles
23
28
  let sourceKeys = []
@@ -28,8 +33,8 @@ module.exports = async function init () {
28
33
  if (interactive && !envFile) {
29
34
  const candidates = discoverEnvFiles()
30
35
  const selected = await prompts.multiselect({
31
- message: 'Create Envfile from .env files and code',
32
- submitLabel: 'Create Envfile',
36
+ message: existing ? 'Recreate Envspec from .env files and code' : 'Create Envspec from .env files and code',
37
+ submitLabel: existing ? 'Recreate Envspec' : 'Create Envspec',
33
38
  choices: [...candidates, { name: 'code ./**/* (env references)', value: '__scan_source' }],
34
39
  initial: [...candidates, '__scan_source']
35
40
  })
@@ -37,7 +42,6 @@ module.exports = async function init () {
37
42
  scanCode = selected.includes('__scan_source')
38
43
  }
39
44
 
40
- const options = this.opts()
41
45
  const spinnerOptions = typeof this.optsWithGlobals === 'function' ? this.optsWithGlobals() : options
42
46
  spinner = await createSpinner({ ...spinnerOptions, ...options, text: 'scanning' })
43
47
  if (scanCode) {
@@ -45,10 +49,16 @@ module.exports = async function init () {
45
49
  sourceKeys = keys
46
50
  }
47
51
 
48
- const { created } = initEnvfile({ envFile, envFiles, sourceKeys, onFile })
52
+ const { created, replaced, content } = initEnvspec({ envFile, envFiles, sourceKeys, overwrite, stdout, onFile })
49
53
  if (spinner) spinner.stop()
50
- if (created) logger.success('◈ created (Envfile)')
51
- else logger.info('○ Envfile already exists (unchanged)')
54
+ if (stdout) {
55
+ process.stdout.write(content)
56
+ return
57
+ }
58
+ if (created) {
59
+ logger.success(replaced ? '◈ recreated (Envspec)' : '◈ created (Envspec)')
60
+ logger.help('⮕ next run [dotenvx check]')
61
+ } else logger.info('○ Envspec already exists [edit or run: spec --overwrite]')
52
62
  } catch (error) {
53
63
  if (spinner) spinner.stop()
54
64
  catchAndLog(error)
@@ -1,6 +1,7 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
- const hasPlaintextSecrets = require('../../lib/helpers/hasPlaintextSecrets')
3
+ const plaintextKeys = require('../../lib/helpers/plaintextKeys')
4
+ const protectEnvspec = require('../../lib/envspec/validation/protectEnvspec')
4
5
  const { logger } = require('../../shared/logger')
5
6
  const createProtectSpinner = require('../../lib/helpers/createProtectSpinner')
6
7
  const logProtectedFiles = require('../../lib/helpers/logProtectedFiles')
@@ -22,12 +23,27 @@ function fixMessage (filepath, privateKeyFile) {
22
23
  function check (filepath, content, beforeError = () => {}) {
23
24
  const filename = path.posix.basename(filepath)
24
25
  const privateKeyFile = filename.startsWith('.env.keys')
25
- if (privateKeyFile || (!exempt(filepath) && hasPlaintextSecrets(content.toString('utf8')))) {
26
+ let rejected = null
27
+ if (!privateKeyFile) {
28
+ try {
29
+ rejected = protectEnvspec(filepath, content.toString('utf8'))
30
+ } catch (error) {
31
+ beforeError()
32
+ logger.error(error.message)
33
+ return false
34
+ }
35
+ }
36
+ const plaintext = rejected === null
37
+ ? !exempt(filepath) && plaintextKeys(content.toString('utf8')).length > 0
38
+ : rejected.length > 0
39
+ if (privateKeyFile || plaintext) {
26
40
  const code = privateKeyFile ? 'PRIVATE_KEY_FILE' : 'PLAINTEXT_ENV'
27
41
  const fix = fixMessage(filepath, privateKeyFile)
28
42
  const message = privateKeyFile
29
43
  ? `refusing to stage ${JSON.stringify(filepath)}`
30
- : `${JSON.stringify(filepath)} contains plaintext secrets`
44
+ : rejected?.length
45
+ ? `${rejected.join(', ')} not encrypted (${JSON.stringify(filepath)})`
46
+ : `${JSON.stringify(filepath)} contains plaintext secrets`
31
47
  beforeError()
32
48
  logger.error(`[${code}] ${message}. ${fix}`)
33
49
  return false
@@ -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
@@ -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)