@dotenvx/dotenvx 2.32.2 → 2.32.3
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.
- package/CHANGELOG.md +8 -1
- package/README.md +41 -24
- package/package.json +1 -1
- package/src/cli/actions/check.js +1 -1
- package/src/cli/actions/init.js +7 -7
- package/src/cli/dotenvx.js +5 -5
- package/src/lib/envspec/discovery/discoverEnvFiles.js +1 -1
- package/src/lib/envspec/discovery/scanSource.js +1 -1
- package/src/lib/envspec/parsing/envspec.peggy +4 -4
- package/src/lib/envspec/parsing/envspecParser.js +4 -4
- package/src/lib/envspec/parsing/readEnvspec.js +30 -18
- package/src/lib/envspec/parsing/resolveEnvspecPath.js +12 -0
- package/src/lib/envspec/rendering/renderEnvspec.js +2 -2
- package/src/lib/envspec/validation/protectEnvspec.js +6 -3
- package/src/lib/helpers/errors.js +1 -1
- package/src/lib/main.d.ts +6 -0
- package/src/lib/main.js +38 -6
- package/src/lib/services/init.js +3 -3
- package/src/lib/services/validate.js +3 -3
- package/src/lib/transforms/encrypt.js +1 -6
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,14 @@
|
|
|
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.32.
|
|
5
|
+
[Unreleased](https://github.com/dotenvx/dotenvx/compare/v2.32.3...main)
|
|
6
|
+
|
|
7
|
+
## [2.32.3](https://github.com/dotenvx/dotenvx/compare/v2.32.2...v2.32.3) (2026-09-30)
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
* Make `Dotenvspec` the filename ([#1002](https://github.com/dotenvx/dotenvx/pull/1002))
|
|
12
|
+
* Improve startup time for cli ([#1001](https://github.com/dotenvx/dotenvx/pull/1001))
|
|
6
13
|
|
|
7
14
|
## [2.32.2](https://github.com/dotenvx/dotenvx/compare/v2.32.1...v2.32.2) (2026-09-29)
|
|
8
15
|
|
package/README.md
CHANGED
|
@@ -1305,9 +1305,9 @@ Hello String
|
|
|
1305
1305
|
```
|
|
1306
1306
|
|
|
1307
1307
|
</details>
|
|
1308
|
-
<details><summary>`run with
|
|
1308
|
+
<details><summary>`run with Dotenvspec redaction`</summary><br>
|
|
1309
1309
|
|
|
1310
|
-
Run any command with real environment variables while automatically redacting values selected by your
|
|
1310
|
+
Run any command with real environment variables while automatically redacting values selected by your Dotenvspec from stdout and stderr.
|
|
1311
1311
|
|
|
1312
1312
|
```sh
|
|
1313
1313
|
$ echo "SECRET=super-secret-value" > .env
|
|
@@ -1319,9 +1319,9 @@ $ dotenvx run --quiet -- node index.js
|
|
|
1319
1319
|
[REDACTED] visible-value
|
|
1320
1320
|
```
|
|
1321
1321
|
|
|
1322
|
-
With
|
|
1322
|
+
With a Dotenvspec, 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
1323
|
|
|
1324
|
-
Without
|
|
1324
|
+
Without a Dotenvspec, `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 a Dotenvspec or `--redact`, output is not redacted. A Dotenvspec always takes precedence: its rules apply automatically, even when `--redact` is passed.
|
|
1325
1325
|
|
|
1326
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.
|
|
1327
1327
|
|
|
@@ -1567,12 +1567,24 @@ Hello production
|
|
|
1567
1567
|
Available log levels are `error, warn, info, verbose, debug, silly` ([source](https://docs.npmjs.com/cli/v8/using-npm/logging#setting-log-levels))
|
|
1568
1568
|
|
|
1569
1569
|
</details>
|
|
1570
|
-
<details><summary>`run with
|
|
1570
|
+
<details><summary>`run with a Dotenvspec`</summary><br>
|
|
1571
1571
|
|
|
1572
|
-
|
|
1572
|
+
`Dotenvspec` is the default policy filename. `Envspec` is also supported as a shorthand when `Dotenvspec` is absent. `Dotenvxspec` is accepted as a final fallback when neither exists. Only the first matching file is read; an invalid or unreadable policy never falls back to another filename. This precedence applies to `run`, `check`, `config()`, encryption, and Git protection.
|
|
1573
|
+
|
|
1574
|
+
Set `DOTENV_SPEC` to inline policy text to use it instead of a policy file:
|
|
1575
|
+
|
|
1576
|
+
```sh
|
|
1577
|
+
DOTENV_SPEC='env "PORT", type: "port", encrypted: false, redacted: false' dotenvx run -- node index.js
|
|
1578
|
+
```
|
|
1579
|
+
|
|
1580
|
+
The precedence is `DOTENV_SPEC` → `Dotenvspec` → `Envspec` → `Dotenvxspec`. The variable contains the policy itself, not a file path, and supports multiline declarations and file blocks. File block paths are relative to the current working directory. Invalid inline policy fails without falling back to a file; an explicitly empty value selects an empty policy with the usual default rules. Unset the variable to resume file discovery.
|
|
1581
|
+
|
|
1582
|
+
Inline policy is read from the incoming environment before loading `.env` files or `--env` values. For `config({ processEnv })`, put `DOTENV_SPEC` in that object. The same override applies to `check`, encryption, and Git protection. `dotenvx spec` still generates `Dotenvspec` from its selected inputs.
|
|
1583
|
+
|
|
1584
|
+
When a `Dotenvspec` 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.
|
|
1573
1585
|
|
|
1574
1586
|
```ruby
|
|
1575
|
-
#
|
|
1587
|
+
# Dotenvspec
|
|
1576
1588
|
env "DATABASE_URL", type: "url"
|
|
1577
1589
|
env "API_KEY"
|
|
1578
1590
|
env "SENTRY_DSN", optional: true
|
|
@@ -1583,9 +1595,11 @@ $ dotenvx run -- node index.js
|
|
|
1583
1595
|
[INVALID_ENV] DATABASE_URL is required; API_KEY is required
|
|
1584
1596
|
```
|
|
1585
1597
|
|
|
1586
|
-
|
|
1598
|
+
Dotenvspec validation failures, including unencrypted values, warn by default; `run --strict` stops before launching the command. A `strict true` setting in Dotenvspec, 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 Dotenvspec syntax always stops execution.
|
|
1587
1599
|
|
|
1588
|
-
|
|
1600
|
+
Dotenvspec 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.
|
|
1601
|
+
|
|
1602
|
+
The synchronous `dotenvx.config()` API also reads `Dotenvspec` from the current working directory and validates the final resolved values using the same rules, including selected file blocks and storage encryption. Validation failures warn and are returned in `{ parsed, error }`; `config({ strict: true })` or an applicable Dotenvspec `strict true` setting makes failures throw. `ignore: ['INVALID_ENV']` suppresses validation failures. Invalid Dotenvspec syntax always throws before loading values. Dotenvspec redaction applies to dotenvx's own resolved-value debug logs; application output and returned values retain their real values. Active proxy declarations throw before loading values because synchronous `config()` cannot start the proxy; use `dotenvx run -- yourcommand` for those policies.
|
|
1589
1603
|
|
|
1590
1604
|
```ruby
|
|
1591
1605
|
file ".env.development" do
|
|
@@ -1598,15 +1612,17 @@ end
|
|
|
1598
1612
|
|
|
1599
1613
|
`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
1614
|
|
|
1601
|
-
|
|
1615
|
+
`dotenvx spec` always generates `Dotenvspec`, including with `--overwrite` or `--stdout`. Existing `Envspec` and `Dotenvxspec` files are left untouched; creating `Dotenvspec` makes it the active policy.
|
|
1616
|
+
|
|
1617
|
+
If a Dotenvspec already exists, `spec` leaves it untouched and prints `○ Dotenvspec 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 Dotenvspec from .env files and code`. Noninteractive runs use `.env.example` and `.env`, or the file selected with `-f`. Input validation finishes before the old Dotenvspec is replaced; cancelled selection leaves it untouched. Symlinked Dotenvspecs cannot be overwritten.
|
|
1602
1618
|
|
|
1603
|
-
Use `dotenvx spec --stdout` to print the generated
|
|
1619
|
+
Use `dotenvx spec --stdout` to print the generated Dotenvspec without writing it, or `dotenvx spec --stdout -f .env.production` to select an input file. This works even when a Dotenvspec already exists; `--stdout` leaves it untouched even with `--overwrite`. Prompts and progress stay on stderr so stdout contains only the generated content.
|
|
1604
1620
|
|
|
1605
1621
|
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
1622
|
|
|
1607
1623
|
|
|
1608
1624
|
</details>
|
|
1609
|
-
<details><summary>`run with
|
|
1625
|
+
<details><summary>`run with Dotenvspec file rules`</summary><br>
|
|
1610
1626
|
|
|
1611
1627
|
Use exact file blocks to override rules for selected files:
|
|
1612
1628
|
|
|
@@ -1623,14 +1639,14 @@ end
|
|
|
1623
1639
|
|
|
1624
1640
|
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.
|
|
1625
1641
|
|
|
1626
|
-
Paths in file blocks are relative to the
|
|
1642
|
+
Paths in file blocks are relative to the Dotenvspec. 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.
|
|
1627
1643
|
|
|
1628
1644
|
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.
|
|
1629
1645
|
|
|
1630
1646
|
</details>
|
|
1631
1647
|
<details><summary>`check`</summary><br>
|
|
1632
1648
|
|
|
1633
|
-
Validate the final resolved environment against your
|
|
1649
|
+
Validate the final resolved environment against your Dotenvspec, using the same loader and precedence as `run`:
|
|
1634
1650
|
|
|
1635
1651
|
```sh
|
|
1636
1652
|
$ dotenvx check -f .env.local -f .env
|
|
@@ -1640,7 +1656,7 @@ $ dotenvx check -f .env.production
|
|
|
1640
1656
|
☠ TOKEN_SECRET not encrypted (.env.production:4)
|
|
1641
1657
|
```
|
|
1642
1658
|
|
|
1643
|
-
|
|
1659
|
+
Dotenvspec `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
1660
|
|
|
1645
1661
|
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
1662
|
|
|
@@ -1649,9 +1665,9 @@ Missing files explicitly selected with `-f` or `DOTENV_FILE` (and its aliases) f
|
|
|
1649
1665
|
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
1666
|
|
|
1651
1667
|
</details>
|
|
1652
|
-
<details><summary>`protect with
|
|
1668
|
+
<details><summary>`protect with a Dotenvspec`</summary><br>
|
|
1653
1669
|
|
|
1654
|
-
The Git protection filter reads `
|
|
1670
|
+
The Git protection filter reads `Dotenvspec` 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
1671
|
|
|
1656
1672
|
```ruby
|
|
1657
1673
|
env "BASE_URL", encrypted: false
|
|
@@ -1660,11 +1676,11 @@ env "TOKEN_SECRET"
|
|
|
1660
1676
|
|
|
1661
1677
|
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
1678
|
|
|
1663
|
-
Without
|
|
1679
|
+
Without a Dotenvspec, 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
1680
|
|
|
1665
1681
|
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
1682
|
|
|
1667
|
-
The policy is read from the working-tree
|
|
1683
|
+
The policy is read from the working-tree Dotenvspec 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. Dotenvspec encryption rules also apply to otherwise exempt files such as `.env.example`.
|
|
1668
1684
|
|
|
1669
1685
|
Accepted blobs pass through byte-for-byte. This integration applies to Git protection, not `protect --docker`.
|
|
1670
1686
|
|
|
@@ -2272,7 +2288,7 @@ $ dotenvx set HELLO_PLAIN World
|
|
|
2272
2288
|
set HELLO_PLAIN (.env)
|
|
2273
2289
|
```
|
|
2274
2290
|
|
|
2275
|
-
Keys ending in `_PLAIN` are not encrypted by `dotenvx set`. `dotenvx encrypt` also skips these keys when there is no
|
|
2291
|
+
Keys ending in `_PLAIN` are not encrypted by `dotenvx set`. `dotenvx encrypt` also skips these keys when there is no Dotenvspec; with a Dotenvspec, its encryption rules take precedence.
|
|
2276
2292
|
|
|
2277
2293
|
</details>
|
|
2278
2294
|
<details><summary>`set KEY value --no-native`</summary><br>
|
|
@@ -2331,7 +2347,7 @@ $ dotenvx del HELLO -f .env.production
|
|
|
2331
2347
|
|
|
2332
2348
|
Encrypt the contents of a `.env` file to an encrypted `.env` file.
|
|
2333
2349
|
|
|
2334
|
-
When the current directory contains
|
|
2350
|
+
When the current directory contains a Dotenvspec, `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 Dotenvspecs fail rather than falling back to encrypting everything. The Dotenvspec itself is never modified.
|
|
2335
2351
|
|
|
2336
2352
|
```sh
|
|
2337
2353
|
$ echo "HELLO=World" > .env
|
|
@@ -3244,6 +3260,7 @@ DOTENV_CONVENTION= # set to a default convention like 'nextjs' or 'flow'
|
|
|
3244
3260
|
DOTENV_FILE= # path to your env file; comma-separate multiple paths
|
|
3245
3261
|
DOTENV_PATH= # synonym for DOTENV_FILE
|
|
3246
3262
|
DOTENV_F= # synonym for DOTENV_FILE
|
|
3263
|
+
DOTENV_SPEC= # inline Dotenvspec policy text; overrides Dotenvspec, Envspec, and Dotenvxspec files
|
|
3247
3264
|
DOTENV_IGNORE= # MISSING_ENV_FILE,OTHER
|
|
3248
3265
|
DOTENV_QUIET= # set to "true" to default to --quiet
|
|
3249
3266
|
|
|
@@ -3286,7 +3303,7 @@ INVALID_PUBLIC_KEY= # a public key is malformed or otherwise invalid
|
|
|
3286
3303
|
MALFORMED_ENCRYPTED_DATA= # the encrypted value is malformed
|
|
3287
3304
|
MISPAIRED_PRIVATE_KEY= # a private key does not match the existing public key
|
|
3288
3305
|
MISSING_DIRECTORY= # the requested directory does not exist
|
|
3289
|
-
ENVSPEC_REQUIRED= # the required
|
|
3306
|
+
ENVSPEC_REQUIRED= # the required Dotenvspec does not exist
|
|
3290
3307
|
MISSING_ENV_FILE= # a requested environment file does not exist
|
|
3291
3308
|
MISSING_ENV_FILES= # no .env* files were found
|
|
3292
3309
|
MISSING_ENV_KEYS_FILE= # the requested .env.keys file does not exist
|
|
@@ -3298,8 +3315,8 @@ MISSING_REQUIRED= # validation detail for which required variables are missing;
|
|
|
3298
3315
|
MISSING_VALUE= # no value was supplied for a key
|
|
3299
3316
|
NOT_FOUND= # a private key was not found in the native secret store
|
|
3300
3317
|
PRECOMMIT_HOOK_MODIFY_FAILED= # dotenvx could not update the pre-commit hook
|
|
3301
|
-
INVALID_ENV= # resolved values do not satisfy
|
|
3302
|
-
MALFORMED_ENVSPEC= #
|
|
3318
|
+
INVALID_ENV= # resolved values do not satisfy Dotenvspec rules
|
|
3319
|
+
MALFORMED_ENVSPEC= # Dotenvspec syntax or configuration is invalid
|
|
3303
3320
|
WRONG_PRIVATE_KEY= # the supplied private key cannot decrypt the value
|
|
3304
3321
|
```
|
|
3305
3322
|
|
package/package.json
CHANGED
package/src/cli/actions/check.js
CHANGED
|
@@ -34,7 +34,7 @@ async function check () {
|
|
|
34
34
|
checked.push(...readableFilepaths)
|
|
35
35
|
if (processedEnvs.some(row => row.type === 'env' && Object.keys(row.parsed || {}).length)) checked.push('--env')
|
|
36
36
|
if (checked.length === 0 && [...schema.redactionRules.keys()].some(key => processEnv[key] !== undefined)) checked.push('shell environment')
|
|
37
|
-
const location = diagnosticLocations(processedEnvs, checked.join(', ') || '
|
|
37
|
+
const location = diagnosticLocations(processedEnvs, checked.join(', ') || 'Dotenvspec')
|
|
38
38
|
for (const row of processedEnvs) {
|
|
39
39
|
for (const error of row.errors || []) {
|
|
40
40
|
if (ignore.includes(error.code)) continue
|
package/src/cli/actions/init.js
CHANGED
|
@@ -17,12 +17,12 @@ module.exports = async function spec () {
|
|
|
17
17
|
let spinner
|
|
18
18
|
|
|
19
19
|
try {
|
|
20
|
-
const existing = stdout ? undefined : fs.lstatSync('
|
|
20
|
+
const existing = stdout ? undefined : fs.lstatSync('Dotenvspec', { throwIfNoEntry: false })
|
|
21
21
|
if (existing && !overwrite) {
|
|
22
|
-
logger.info('○
|
|
22
|
+
logger.info('○ Dotenvspec already exists [edit or run: spec --overwrite]')
|
|
23
23
|
return
|
|
24
24
|
}
|
|
25
|
-
if (existing && !existing.isFile()) throw new Error('Cannot replace
|
|
25
|
+
if (existing && !existing.isFile()) throw new Error('Cannot replace Dotenvspec: expected a regular file')
|
|
26
26
|
|
|
27
27
|
let envFiles
|
|
28
28
|
let sourceKeys = []
|
|
@@ -33,8 +33,8 @@ module.exports = async function spec () {
|
|
|
33
33
|
if (interactive && !envFile) {
|
|
34
34
|
const candidates = discoverEnvFiles()
|
|
35
35
|
const selected = await prompts.multiselect({
|
|
36
|
-
message: existing ? 'Recreate
|
|
37
|
-
submitLabel: existing ? 'Recreate
|
|
36
|
+
message: existing ? 'Recreate Dotenvspec from .env files and code' : 'Create Dotenvspec from .env files and code',
|
|
37
|
+
submitLabel: existing ? 'Recreate Dotenvspec' : 'Create Dotenvspec',
|
|
38
38
|
choices: [...candidates, { name: 'code ./**/* (env references)', value: '__scan_source' }],
|
|
39
39
|
initial: [...candidates, '__scan_source']
|
|
40
40
|
})
|
|
@@ -56,9 +56,9 @@ module.exports = async function spec () {
|
|
|
56
56
|
return
|
|
57
57
|
}
|
|
58
58
|
if (created) {
|
|
59
|
-
logger.success(replaced ? '◈ recreated (
|
|
59
|
+
logger.success(replaced ? '◈ recreated (Dotenvspec)' : '◈ created (Dotenvspec)')
|
|
60
60
|
logger.help('⮕ next run [dotenvx check]')
|
|
61
|
-
} else logger.info('○
|
|
61
|
+
} else logger.info('○ Dotenvspec already exists [edit or run: spec --overwrite]')
|
|
62
62
|
} catch (error) {
|
|
63
63
|
if (spinner) spinner.stop()
|
|
64
64
|
catchAndLog(error)
|
package/src/cli/dotenvx.js
CHANGED
|
@@ -78,7 +78,7 @@ program.command('run')
|
|
|
78
78
|
.option('--ignore <errorCodes...>', 'error code(s) to ignore (example: --ignore=MISSING_ENV_FILE)')
|
|
79
79
|
.option('--token <token>', 'set Armor ⛨ token')
|
|
80
80
|
.option('--mask [characters]', 'inject masked values, optionally setting visible characters')
|
|
81
|
-
.option('--redact', 'redact injected values except public keys (
|
|
81
|
+
.option('--redact', 'redact injected values except public keys (Dotenvspec 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')
|
|
@@ -226,9 +226,9 @@ program.command('ls', { hidden: true })
|
|
|
226
226
|
|
|
227
227
|
// dotenvx spec
|
|
228
228
|
program.command('spec', { hidden: true })
|
|
229
|
-
.description('create
|
|
229
|
+
.description('create a Dotenvspec')
|
|
230
230
|
.option('--stdout', 'send to stdout')
|
|
231
|
-
.option('--overwrite', 'replace existing
|
|
231
|
+
.option('--overwrite', 'replace existing Dotenvspec, including custom rules, comments, and missing-file blocks')
|
|
232
232
|
.option('-f, --env-file <path>', 'file to read variable names from')
|
|
233
233
|
.action(function () {
|
|
234
234
|
return commandAction(require('./actions/init')).apply(this, arguments)
|
|
@@ -236,7 +236,7 @@ program.command('spec', { hidden: true })
|
|
|
236
236
|
|
|
237
237
|
// dotenvx check
|
|
238
238
|
program.command('check', { hidden: true })
|
|
239
|
-
.description('check
|
|
239
|
+
.description('check Dotenvspec rules against .env file(s)')
|
|
240
240
|
.option('-e, --env <strings...>', 'environment variable(s) set as string (example: "HELLO=World")', collectEnvs('env'), [])
|
|
241
241
|
.option('-f, --env-file <path>', 'path(s) to your env file(s)', collectEnvs('envFile'), [])
|
|
242
242
|
.option('-fk, --env-keys-file <path>', 'path(s) to your .env.keys file(s) (default: same path as your env file)', collectEnvKeys)
|
|
@@ -336,7 +336,7 @@ function hiddenSubcommands (name) {
|
|
|
336
336
|
program.command('hidden')
|
|
337
337
|
.allowExcessArguments(false)
|
|
338
338
|
.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
|
|
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>`)
|
|
340
340
|
.action(function () { this.outputHelp() })
|
|
341
341
|
|
|
342
342
|
// dotenvx update
|
|
@@ -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 =>
|
|
14
|
+
if (current !== root && entries.some(entry => ['Dotenvspec', 'Envspec', 'Dotenvxspec', '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', 'Envspec', '.env.schema'])
|
|
7
|
+
const projectMarkers = new Set(['package.json', 'Dotenvspec', 'Envspec', 'Dotenvxspec', '.env.schema'])
|
|
8
8
|
const languages = {
|
|
9
9
|
js: 'js',
|
|
10
10
|
mjs: 'js',
|
|
@@ -2,7 +2,7 @@ Document
|
|
|
2
2
|
= _ entries:((FileBlock / Declaration / Strict) _)* {
|
|
3
3
|
const items = entries.map(item => item[0]);
|
|
4
4
|
const settings = items.filter(item => item.strict !== undefined && !item.file);
|
|
5
|
-
if (settings.length > 1) error("Duplicate
|
|
5
|
+
if (settings.length > 1) error("Duplicate Dotenvspec setting: strict");
|
|
6
6
|
return { ...settings[0], declarations: items.filter(item => item.name), files: items.filter(item => item.file) };
|
|
7
7
|
}
|
|
8
8
|
|
|
@@ -10,7 +10,7 @@ FileBlock
|
|
|
10
10
|
= "file" [ \t]+ file:Filename [ \t]+ "do" [ \t]* Comment? Newline _ entries:((Declaration / Strict) _)* "end" [ \t]* Comment? (Newline / !.) {
|
|
11
11
|
const items = entries.map(item => item[0]);
|
|
12
12
|
const settings = items.filter(item => item.strict !== undefined);
|
|
13
|
-
if (settings.length > 1) error("Duplicate
|
|
13
|
+
if (settings.length > 1) error("Duplicate Dotenvspec setting: strict");
|
|
14
14
|
return { file, ...settings[0], declarations: items.filter(item => item.name) };
|
|
15
15
|
}
|
|
16
16
|
|
|
@@ -26,10 +26,10 @@ Declaration
|
|
|
26
26
|
const declaration = { name };
|
|
27
27
|
const seen = new Set();
|
|
28
28
|
for (const option of options) {
|
|
29
|
-
if (seen.has(option.key)) error(`Duplicate
|
|
29
|
+
if (seen.has(option.key)) error(`Duplicate Dotenvspec option: ${option.key}`);
|
|
30
30
|
if ((option.key === "optional" && seen.has("required")) ||
|
|
31
31
|
(option.key === "required" && seen.has("optional"))) {
|
|
32
|
-
error("Cannot combine required and optional in
|
|
32
|
+
error("Cannot combine required and optional in a Dotenvspec declaration");
|
|
33
33
|
}
|
|
34
34
|
seen.add(option.key);
|
|
35
35
|
if (option.key === "optional") declaration.required = !option.value;
|
|
@@ -288,13 +288,13 @@ function peg$parse(input, options) {
|
|
|
288
288
|
function peg$f0(entries) {
|
|
289
289
|
const items = entries.map(item => item[0]);
|
|
290
290
|
const settings = items.filter(item => item.strict !== undefined && !item.file);
|
|
291
|
-
if (settings.length > 1) error("Duplicate
|
|
291
|
+
if (settings.length > 1) error("Duplicate Dotenvspec setting: strict");
|
|
292
292
|
return { ...settings[0], declarations: items.filter(item => item.name), files: items.filter(item => item.file) };
|
|
293
293
|
}
|
|
294
294
|
function peg$f1(file, entries) {
|
|
295
295
|
const items = entries.map(item => item[0]);
|
|
296
296
|
const settings = items.filter(item => item.strict !== undefined);
|
|
297
|
-
if (settings.length > 1) error("Duplicate
|
|
297
|
+
if (settings.length > 1) error("Duplicate Dotenvspec setting: strict");
|
|
298
298
|
return { file, ...settings[0], declarations: items.filter(item => item.name) };
|
|
299
299
|
}
|
|
300
300
|
function peg$f2(value) { return { strict: value }; }
|
|
@@ -304,10 +304,10 @@ function peg$parse(input, options) {
|
|
|
304
304
|
const declaration = { name };
|
|
305
305
|
const seen = new Set();
|
|
306
306
|
for (const option of options) {
|
|
307
|
-
if (seen.has(option.key)) error(`Duplicate
|
|
307
|
+
if (seen.has(option.key)) error(`Duplicate Dotenvspec option: ${option.key}`);
|
|
308
308
|
if ((option.key === "optional" && seen.has("required")) ||
|
|
309
309
|
(option.key === "required" && seen.has("optional"))) {
|
|
310
|
-
error("Cannot combine required and optional in
|
|
310
|
+
error("Cannot combine required and optional in a Dotenvspec declaration");
|
|
311
311
|
}
|
|
312
312
|
seen.add(option.key);
|
|
313
313
|
if (option.key === "optional") declaration.required = !option.value;
|
|
@@ -6,6 +6,7 @@ const Errors = require('../../helpers/errors')
|
|
|
6
6
|
const isValidUrl = require('../../helpers/isValidUrl')
|
|
7
7
|
const isValidEmail = require('../../helpers/isValidEmail')
|
|
8
8
|
const formatEnvspecSyntaxError = require('./formatEnvspecSyntaxError')
|
|
9
|
+
const resolveEnvspecPath = require('./resolveEnvspecPath')
|
|
9
10
|
|
|
10
11
|
function compileDeclarations (declarations) {
|
|
11
12
|
const proxyRules = new Map()
|
|
@@ -21,7 +22,7 @@ function compileDeclarations (declarations) {
|
|
|
21
22
|
for (const input of declarations) {
|
|
22
23
|
const declaration = { ...input }
|
|
23
24
|
if (input.type) declaredTypes.set(input.name, input.type)
|
|
24
|
-
if (names.has(declaration.name)) throw new Errors({ message: `Duplicate
|
|
25
|
+
if (names.has(declaration.name)) throw new Errors({ message: `Duplicate Dotenvspec declaration: ${declaration.name}` }).malformedEnvspec()
|
|
25
26
|
names.add(declaration.name)
|
|
26
27
|
redactionRules.set(declaration.name, declaration.redacted !== false)
|
|
27
28
|
encryptionRules.set(declaration.name, declaration.encrypted !== false)
|
|
@@ -35,35 +36,35 @@ function compileDeclarations (declarations) {
|
|
|
35
36
|
if (declaration.type) types.set(declaration.name, declaration.type)
|
|
36
37
|
if (declaration.min !== undefined || declaration.max !== undefined) {
|
|
37
38
|
if (declaration.type !== 'integer') {
|
|
38
|
-
throw new Errors({ message: `Invalid
|
|
39
|
+
throw new Errors({ message: `Invalid Dotenvspec range for ${declaration.name}: min and max require type: "integer" or "port".` }).malformedEnvspec()
|
|
39
40
|
}
|
|
40
41
|
if (declaration.min !== undefined && declaration.max !== undefined && BigInt(declaration.min) > BigInt(declaration.max)) {
|
|
41
|
-
throw new Errors({ message: `Invalid
|
|
42
|
+
throw new Errors({ message: `Invalid Dotenvspec range for ${declaration.name}: min must be less than or equal to max.` }).malformedEnvspec()
|
|
42
43
|
}
|
|
43
44
|
ranges.set(declaration.name, { min: declaration.min, max: declaration.max })
|
|
44
45
|
}
|
|
45
46
|
if (declaration.enum) {
|
|
46
47
|
if (declaration.type === 'integer' && declaration.enum.some(value => !/^[+-]?\d+$/.test(value.trim()))) {
|
|
47
|
-
throw new Errors({ message: `Invalid
|
|
48
|
+
throw new Errors({ message: `Invalid Dotenvspec enum for ${declaration.name}: expected integer choices.` }).malformedEnvspec()
|
|
48
49
|
}
|
|
49
50
|
if (declaration.type === 'boolean' && declaration.enum.some(value => !['true', 'false', '1', '0'].includes(value))) {
|
|
50
|
-
throw new Errors({ message: `Invalid
|
|
51
|
+
throw new Errors({ message: `Invalid Dotenvspec enum for ${declaration.name}: expected true, false, 1, or 0 choices.` }).malformedEnvspec()
|
|
51
52
|
}
|
|
52
53
|
if (declaration.type === 'url' && declaration.enum.some(value => !isValidUrl(value))) {
|
|
53
|
-
throw new Errors({ message: `Invalid
|
|
54
|
+
throw new Errors({ message: `Invalid Dotenvspec enum for ${declaration.name}: expected URL choices.` }).malformedEnvspec()
|
|
54
55
|
}
|
|
55
56
|
if (declaration.type === 'email' && declaration.enum.some(value => !isValidEmail(value))) {
|
|
56
|
-
throw new Errors({ message: `Invalid
|
|
57
|
+
throw new Errors({ message: `Invalid Dotenvspec enum for ${declaration.name}: expected email choices.` }).malformedEnvspec()
|
|
57
58
|
}
|
|
58
59
|
if (declaration.type === 'ip' && declaration.enum.some(value => isIP(value) === 0)) {
|
|
59
|
-
throw new Errors({ message: `Invalid
|
|
60
|
+
throw new Errors({ message: `Invalid Dotenvspec enum for ${declaration.name}: expected IPv4 or IPv6 choices.` }).malformedEnvspec()
|
|
60
61
|
}
|
|
61
62
|
enums.set(declaration.name, declaration.enum)
|
|
62
63
|
}
|
|
63
64
|
if (declaration.proxy) {
|
|
64
65
|
const host = declaration.proxy.domain.toLowerCase()
|
|
65
66
|
if (host.length > 253 || isIP(host) || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host)) {
|
|
66
|
-
throw new Errors({ message: `Invalid
|
|
67
|
+
throw new Errors({ message: `Invalid Dotenvspec proxy host for ${declaration.name}: expected a DNS hostname without a scheme, port, path or wildcard.` }).malformedEnvspec()
|
|
67
68
|
}
|
|
68
69
|
proxyRules.set(declaration.name, host)
|
|
69
70
|
}
|
|
@@ -71,13 +72,24 @@ function compileDeclarations (declarations) {
|
|
|
71
72
|
return { exists: true, proxyRules, requiredKeys, types, declaredTypes, enums, ranges, encryptedKeys, redactionRules, encryptionRules }
|
|
72
73
|
}
|
|
73
74
|
|
|
74
|
-
module.exports = function readEnvspec (filepath =
|
|
75
|
+
module.exports = function readEnvspec (filepath, envFiles = ['.env'], processEnv = process.env) {
|
|
75
76
|
let src
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
77
|
+
if (filepath === undefined && processEnv.DOTENV_SPEC !== undefined) {
|
|
78
|
+
// Inline policy replaces file discovery, even when the value is empty.
|
|
79
|
+
// Use the working directory for file blocks and DOTENV_SPEC in diagnostics.
|
|
80
|
+
filepath = path.resolve('DOTENV_SPEC')
|
|
81
|
+
src = processEnv.DOTENV_SPEC
|
|
82
|
+
} else {
|
|
83
|
+
if (filepath === undefined) filepath = resolveEnvspecPath()
|
|
84
|
+
try {
|
|
85
|
+
src = fs.readFileSync(filepath, 'utf8')
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error.code === 'ENOENT') {
|
|
88
|
+
if (fs.lstatSync(filepath, { throwIfNoEntry: false })) throw new Error(`Cannot read ${path.basename(filepath)}: ${filepath}`)
|
|
89
|
+
return { ...compileDeclarations([]), exists: false }
|
|
90
|
+
}
|
|
91
|
+
throw error
|
|
92
|
+
}
|
|
81
93
|
}
|
|
82
94
|
|
|
83
95
|
let document
|
|
@@ -99,12 +111,12 @@ module.exports = function readEnvspec (filepath = path.resolve('Envspec'), envFi
|
|
|
99
111
|
throw new Errors({ message: `File blocks require an exact filename: ${block.file}` }).malformedEnvspec()
|
|
100
112
|
}
|
|
101
113
|
const file = path.resolve(path.dirname(filepath), block.file)
|
|
102
|
-
if (seen.has(file)) throw new Errors({ message: `Duplicate
|
|
114
|
+
if (seen.has(file)) throw new Errors({ message: `Duplicate Dotenvspec file block: ${block.file}` }).malformedEnvspec()
|
|
103
115
|
seen.add(file)
|
|
104
116
|
const merged = new Map(base.map(item => [item.name, { ...item }]))
|
|
105
117
|
const names = new Set()
|
|
106
118
|
for (const item of block.declarations) {
|
|
107
|
-
if (names.has(item.name)) throw new Errors({ message: `Duplicate
|
|
119
|
+
if (names.has(item.name)) throw new Errors({ message: `Duplicate Dotenvspec declaration in ${block.file}: ${item.name}` }).malformedEnvspec()
|
|
108
120
|
names.add(item.name)
|
|
109
121
|
merged.set(item.name, {
|
|
110
122
|
...defaults,
|
|
@@ -124,7 +136,7 @@ module.exports = function readEnvspec (filepath = path.resolve('Envspec'), envFi
|
|
|
124
136
|
for (const schema of active) {
|
|
125
137
|
for (const [key, host] of schema.proxyRules) {
|
|
126
138
|
if (proxyRules.has(key) && proxyRules.get(key) !== host) {
|
|
127
|
-
throw new Errors({ message: `Conflicting
|
|
139
|
+
throw new Errors({ message: `Conflicting Dotenvspec proxy domains for ${key} in selected file blocks` }).malformedEnvspec()
|
|
128
140
|
}
|
|
129
141
|
proxyRules.set(key, host)
|
|
130
142
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const fs = require('node:fs')
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
|
|
4
|
+
// A present but broken Dotenvspec must fail, never fall back to a weaker policy.
|
|
5
|
+
module.exports = function resolveEnvspecPath (directory = process.cwd()) {
|
|
6
|
+
const preferred = path.resolve(directory, 'Dotenvspec')
|
|
7
|
+
if (fs.lstatSync(preferred, { throwIfNoEntry: false })) return preferred
|
|
8
|
+
const shorthand = path.resolve(directory, 'Envspec')
|
|
9
|
+
if (fs.lstatSync(shorthand, { throwIfNoEntry: false })) return shorthand
|
|
10
|
+
const alternate = path.resolve(directory, 'Dotenvxspec')
|
|
11
|
+
return fs.lstatSync(alternate, { throwIfNoEntry: false }) ? alternate : preferred
|
|
12
|
+
}
|
|
@@ -10,7 +10,7 @@ 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
|
|
13
|
+
throw new Error(`Unsupported Dotenvspec 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')
|
|
@@ -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 '#
|
|
29
|
+
return '# Dotenvspec (safe to commit)\n# ------------------------\n\n' + sections.join('\n\n') + (sections.length ? '\n' : '')
|
|
30
30
|
}
|
|
@@ -2,13 +2,14 @@ const fs = require('node:fs')
|
|
|
2
2
|
const path = require('node:path')
|
|
3
3
|
const { execFileSync } = require('node:child_process')
|
|
4
4
|
const readEnvspec = require('../parsing/readEnvspec')
|
|
5
|
+
const resolveEnvspecPath = require('../parsing/resolveEnvspecPath')
|
|
5
6
|
const plaintextKeys = require('../../helpers/plaintextKeys')
|
|
6
7
|
|
|
7
8
|
function readPolicy (policyPath, file) {
|
|
8
9
|
const schema = readEnvspec(policyPath, [file])
|
|
9
10
|
if (!schema.exists) {
|
|
10
11
|
// A dangling policy symlink is a broken policy, not an absent policy.
|
|
11
|
-
if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read
|
|
12
|
+
if (fs.lstatSync(policyPath, { throwIfNoEntry: false })) throw new Error(`Cannot read Dotenvspec: ${policyPath}`)
|
|
12
13
|
return null
|
|
13
14
|
}
|
|
14
15
|
return schema
|
|
@@ -18,7 +19,9 @@ function readPolicy (policyPath, file) {
|
|
|
18
19
|
module.exports = function protectEnvspec (filepath, content) {
|
|
19
20
|
const file = path.resolve(filepath)
|
|
20
21
|
const directory = path.dirname(file)
|
|
21
|
-
let schema =
|
|
22
|
+
let schema = process.env.DOTENV_SPEC !== undefined
|
|
23
|
+
? readEnvspec(undefined, [file])
|
|
24
|
+
: readPolicy(resolveEnvspecPath(directory), file)
|
|
22
25
|
if (!schema) {
|
|
23
26
|
let root
|
|
24
27
|
try {
|
|
@@ -31,7 +34,7 @@ module.exports = function protectEnvspec (filepath, content) {
|
|
|
31
34
|
// Outside a Git working tree, only an adjacent policy can apply.
|
|
32
35
|
return null
|
|
33
36
|
}
|
|
34
|
-
if (path.resolve(root) !== directory) schema = readPolicy(
|
|
37
|
+
if (path.resolve(root) !== directory) schema = readPolicy(resolveEnvspecPath(root), file)
|
|
35
38
|
}
|
|
36
39
|
if (!schema) return null
|
|
37
40
|
|
|
@@ -234,7 +234,7 @@ class Errors {
|
|
|
234
234
|
}
|
|
235
235
|
|
|
236
236
|
envspecRequired () {
|
|
237
|
-
const e = new Error('[ENVSPEC_REQUIRED] check requires
|
|
237
|
+
const e = new Error('[ENVSPEC_REQUIRED] check requires a Dotenvspec or DOTENV_SPEC')
|
|
238
238
|
e.code = 'ENVSPEC_REQUIRED'
|
|
239
239
|
e.help = 'fix: run [dotenvx spec]'
|
|
240
240
|
e.messageWithHelp = `${e.message}. ${e.help}`
|
package/src/lib/main.d.ts
CHANGED
|
@@ -110,6 +110,7 @@ export interface DotenvConfigOptions {
|
|
|
110
110
|
|
|
111
111
|
/**
|
|
112
112
|
* Throw immediately if an error is encountered - like a missing .env file.
|
|
113
|
+
* Includes Dotenvspec validation failures. Dotenvspec strict settings also enforce throwing.
|
|
113
114
|
* @default false
|
|
114
115
|
* @example require('@dotenvx/dotenvx').config({ strict: true })
|
|
115
116
|
*/
|
|
@@ -255,6 +256,11 @@ export interface DotenvPopulateInput {
|
|
|
255
256
|
|
|
256
257
|
/**
|
|
257
258
|
* Loads `.env` file contents into process.env by default.
|
|
259
|
+
* Reads Dotenvspec from the current directory and validates the final resolved environment.
|
|
260
|
+
* Falls back to Envspec, then Dotenvxspec, when earlier filenames are absent.
|
|
261
|
+
* DOTENV_SPEC in processEnv (process.env by default) overrides files with inline policy text.
|
|
262
|
+
* Validation failures warn and return an error, or throw when strictness is enabled.
|
|
263
|
+
* Invalid Dotenvspec syntax and active proxy rules always throw; use run for proxy support.
|
|
258
264
|
*
|
|
259
265
|
* @see https://dotenvx.com/docs
|
|
260
266
|
*
|
package/src/lib/main.js
CHANGED
|
@@ -30,6 +30,10 @@ const normalizeDotenvConfigIgnore = require('./helpers/normalizeDotenvConfigIgno
|
|
|
30
30
|
const normalizeDotenvConfigPath = require('./helpers/normalizeDotenvConfigPath')
|
|
31
31
|
const mask = require('./helpers/mask')
|
|
32
32
|
const maskProcessedEnvs = require('./helpers/maskProcessedEnvs')
|
|
33
|
+
const readEnvspec = require('./envspec/parsing/readEnvspec')
|
|
34
|
+
const validateEnvspec = require('./envspec/validation/validateEnvspec')
|
|
35
|
+
const redactedValues = require('./helpers/redactedValues')
|
|
36
|
+
const { redactOutput } = require('./helpers/redactOutput')
|
|
33
37
|
|
|
34
38
|
function uniqueInjectedKeys (processedEnvs) {
|
|
35
39
|
const result = new Set()
|
|
@@ -75,11 +79,18 @@ const config = function (options = {}, events) {
|
|
|
75
79
|
const noArmor = resolveNoArmor(options)
|
|
76
80
|
const noNative = resolveNoNative(options)
|
|
77
81
|
|
|
82
|
+
let fatal = false
|
|
83
|
+
let sensitiveValues = []
|
|
78
84
|
try {
|
|
79
85
|
let envs = normalizeDotenvConfigPath(buildConfigEnvs(options))
|
|
80
86
|
if (!options.envs) {
|
|
81
87
|
envs = determine(envs, processEnv)
|
|
82
88
|
}
|
|
89
|
+
const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value), processEnv)
|
|
90
|
+
if (schema.proxyRules.size > 0) {
|
|
91
|
+
fatal = true
|
|
92
|
+
throw new Error('Dotenvspec proxy is not supported by synchronous config(). Use dotenvx run -- yourcommand.')
|
|
93
|
+
}
|
|
83
94
|
const {
|
|
84
95
|
processedEnvs,
|
|
85
96
|
readableFilepaths
|
|
@@ -97,6 +108,9 @@ const config = function (options = {}, events) {
|
|
|
97
108
|
token: options.token
|
|
98
109
|
})
|
|
99
110
|
|
|
111
|
+
const validationError = validateEnvspec(schema, processEnv, processedEnvs)
|
|
112
|
+
sensitiveValues = redactedValues(processedEnvs, schema, processEnv)
|
|
113
|
+
|
|
100
114
|
if (options.mask !== undefined) {
|
|
101
115
|
const showChar = options.mask === true ? 6 : options.mask
|
|
102
116
|
maskProcessedEnvs(processedEnvs, processEnv, showChar)
|
|
@@ -116,7 +130,13 @@ const config = function (options = {}, events) {
|
|
|
116
130
|
continue // ignore error
|
|
117
131
|
}
|
|
118
132
|
|
|
119
|
-
|
|
133
|
+
const policyStrict = processedEnv.type === 'envFile'
|
|
134
|
+
? (schema.strictByFile?.get(path.resolve(processedEnv.filepath)) ?? schema.strict)
|
|
135
|
+
: schema.strict
|
|
136
|
+
if (strict || policyStrict) {
|
|
137
|
+
fatal = true
|
|
138
|
+
throw error
|
|
139
|
+
}
|
|
120
140
|
|
|
121
141
|
lastError = error // surface later in { error }
|
|
122
142
|
|
|
@@ -133,18 +153,30 @@ const config = function (options = {}, events) {
|
|
|
133
153
|
Object.assign(parsedAll, processedEnv.existed || {}) // existed 'wins'
|
|
134
154
|
|
|
135
155
|
// debug parsed
|
|
136
|
-
logger.debug(processedEnv.parsed)
|
|
156
|
+
logger.debug(redactOutput(processedEnv.parsed, sensitiveValues))
|
|
137
157
|
|
|
138
158
|
// verbose/debug injected key/value
|
|
139
159
|
for (const [key, value] of Object.entries(processedEnv.injected || {})) {
|
|
140
160
|
logger.verbose(`${key} set`)
|
|
141
|
-
logger.debug(`${key} set to ${value}
|
|
161
|
+
logger.debug(redactOutput(`${key} set to ${value}`, sensitiveValues))
|
|
142
162
|
}
|
|
143
163
|
|
|
144
164
|
// verbose/debug existed key/value
|
|
145
165
|
for (const [key, value] of Object.entries(processedEnv.existed || {})) {
|
|
146
166
|
logger.verbose(`${key} pre-exists (protip: use --overload to override)`)
|
|
147
|
-
logger.debug(`${key} pre-exists as ${value} (protip: use --overload to override)
|
|
167
|
+
logger.debug(redactOutput(`${key} pre-exists as ${value} (protip: use --overload to override)`, sensitiveValues))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (validationError) {
|
|
172
|
+
if (ignore.includes(validationError.code)) {
|
|
173
|
+
logger.verbose(`ignored: ${validationError.message}`)
|
|
174
|
+
} else if (strict || validationError.diagnostics?.some(diagnostic => diagnostic.strict)) {
|
|
175
|
+
fatal = true
|
|
176
|
+
throw validationError
|
|
177
|
+
} else {
|
|
178
|
+
logger.warn(validationError.messageWithHelp || validationError.message)
|
|
179
|
+
lastError = validationError
|
|
148
180
|
}
|
|
149
181
|
}
|
|
150
182
|
|
|
@@ -163,9 +195,9 @@ const config = function (options = {}, events) {
|
|
|
163
195
|
}
|
|
164
196
|
} catch (error) {
|
|
165
197
|
if (events) events.fail(error)
|
|
166
|
-
if (strict
|
|
198
|
+
if (strict || fatal || error.code === 'MALFORMED_ENVSPEC') throw error
|
|
167
199
|
|
|
168
|
-
logger.error(error.messageWithHelp || error.message)
|
|
200
|
+
logger.error(redactOutput(error.messageWithHelp || error.message, sensitiveValues))
|
|
169
201
|
|
|
170
202
|
return { parsed: {}, error }
|
|
171
203
|
}
|
package/src/lib/services/init.js
CHANGED
|
@@ -15,10 +15,10 @@ function declaration (name) {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
module.exports = function init ({ directory = process.cwd(), envFile, envFiles, sourceKeys = [], overwrite = false, stdout = false, onFile = () => {} } = {}) {
|
|
18
|
-
const target = path.resolve(directory, '
|
|
18
|
+
const target = path.resolve(directory, 'Dotenvspec')
|
|
19
19
|
const existing = stdout ? undefined : fs.lstatSync(target, { throwIfNoEntry: false })
|
|
20
20
|
if (existing && !overwrite) return { created: false }
|
|
21
|
-
if (existing && !existing.isFile()) throw new Error(`Cannot replace
|
|
21
|
+
if (existing && !existing.isFile()) throw new Error(`Cannot replace Dotenvspec: expected a regular file (${target})`)
|
|
22
22
|
const seen = new Set()
|
|
23
23
|
|
|
24
24
|
const sources = []
|
|
@@ -61,7 +61,7 @@ module.exports = function init ({ directory = process.cwd(), envFile, envFiles,
|
|
|
61
61
|
const addedFromSource = names.size - inputCount
|
|
62
62
|
const keys = [...names]
|
|
63
63
|
const invalid = keys.filter(key => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
|
|
64
|
-
if (invalid.length) throw new Error(`Unsupported
|
|
64
|
+
if (invalid.length) throw new Error(`Unsupported Dotenvspec variable names: ${invalid.join(', ')}`)
|
|
65
65
|
|
|
66
66
|
const document = normalizeEnvspec({ files, codeDeclarations })
|
|
67
67
|
const content = renderEnvspec(document)
|
|
@@ -20,13 +20,13 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
|
|
|
20
20
|
}))
|
|
21
21
|
envs = buildCommandEnvs(envs, options.convention)
|
|
22
22
|
envs = determine(envs, processEnv)
|
|
23
|
-
const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value))
|
|
23
|
+
const schema = readEnvspec(undefined, envs.filter(env => env.type === 'envFile').map(env => env.value), processEnv)
|
|
24
24
|
if (requireEnvspec && !schema.exists) throw new Errors().envspecRequired()
|
|
25
25
|
|
|
26
26
|
const session = new Session()
|
|
27
27
|
const proxyToken = options.token || processEnv.DOTENVX_TOKEN
|
|
28
28
|
const noArmor = options.armor === false || (!proxyToken && (await session.noArmor()))
|
|
29
|
-
if (schema.proxyRules.size > 0 && noArmor) throw new Error('
|
|
29
|
+
if (schema.proxyRules.size > 0 && noArmor) throw new Error('Dotenvspec proxy requires Armor. Enable Armor and authenticate before running.')
|
|
30
30
|
const proxyCredentials = noArmor ? undefined : []
|
|
31
31
|
const { processedEnvs, readableFilepaths } = await envsResolver({
|
|
32
32
|
envs,
|
|
@@ -48,7 +48,7 @@ module.exports = async function validate ({ envs = [], options = {}, processEnv
|
|
|
48
48
|
let proxyError
|
|
49
49
|
for (const name of schema.proxyRules.keys()) {
|
|
50
50
|
if (processEnv[name] !== undefined && !(proxyCredentials || []).some(credential => credential.name === name && credential.placeholder === processEnv[name])) {
|
|
51
|
-
proxyError = new Error(`
|
|
51
|
+
proxyError = new Error(`Dotenvspec proxy requires an encrypted ${name} loaded from an env file. Remove plaintext or shell overrides, or use --overload.`)
|
|
52
52
|
break
|
|
53
53
|
}
|
|
54
54
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
const fsx = require('./../helpers/fsx')
|
|
2
2
|
const path = require('path')
|
|
3
|
-
const fs = require('node:fs')
|
|
4
3
|
const { encrypted, encrypt, scan, upsert, publickeys, keypair } = require('@dotenvx/primitives')
|
|
5
4
|
|
|
6
5
|
const TYPE_ENV_FILE = 'envFile'
|
|
@@ -53,11 +52,7 @@ async function encryptTransform (options = {}) {
|
|
|
53
52
|
const row = { keys: [], type: TYPE_ENV_FILE, filepath, envFilepath, changed: false }
|
|
54
53
|
|
|
55
54
|
try {
|
|
56
|
-
const
|
|
57
|
-
const schema = readEnvspec(policyPath, [filepath])
|
|
58
|
-
if (!schema.exists && fs.lstatSync(policyPath, { throwIfNoEntry: false })) {
|
|
59
|
-
throw new Error(`Cannot read Envspec: ${policyPath}`)
|
|
60
|
-
}
|
|
55
|
+
const schema = readEnvspec(undefined, [filepath])
|
|
61
56
|
const fileExists = await fsx.exists(filepath)
|
|
62
57
|
if (!fileExists && !noCreate) {
|
|
63
58
|
row.envSrc = SAMPLE_ENV_KIT
|