@cogs/config 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -6
- package/dist/cjs/dotenv-checkers.js +85 -23
- package/dist/cjs/dotenv-correlation.js +95 -0
- package/dist/cjs/dotenv-files.js +43 -0
- package/dist/cjs/dotenv-fixers.js +17 -20
- package/dist/cjs/envs.js +53 -26
- package/dist/cjs/redact.js +27 -0
- package/dist/cli-core.d.ts +72 -0
- package/dist/cli-core.d.ts.map +1 -0
- package/dist/cli-core.js +310 -0
- package/dist/cli-core.js.map +1 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +17 -0
- package/dist/cli.js.map +1 -0
- package/dist/dotenv-checkers.d.ts +61 -11
- package/dist/dotenv-checkers.d.ts.map +1 -1
- package/dist/dotenv-checkers.js +84 -22
- package/dist/dotenv-checkers.js.map +1 -1
- package/dist/dotenv-correlation.d.ts +23 -0
- package/dist/dotenv-correlation.d.ts.map +1 -0
- package/dist/dotenv-correlation.js +92 -0
- package/dist/dotenv-correlation.js.map +1 -0
- package/dist/dotenv-files.d.ts +24 -0
- package/dist/dotenv-files.d.ts.map +1 -0
- package/dist/dotenv-files.js +40 -0
- package/dist/dotenv-files.js.map +1 -0
- package/dist/dotenv-fixers.d.ts.map +1 -1
- package/dist/dotenv-fixers.js +17 -20
- package/dist/dotenv-fixers.js.map +1 -1
- package/dist/envs.d.ts +9 -1
- package/dist/envs.d.ts.map +1 -1
- package/dist/envs.js +55 -28
- package/dist/envs.js.map +1 -1
- package/dist/redact.d.ts +18 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +24 -0
- package/dist/redact.js.map +1 -0
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -53,19 +53,127 @@ correctEnv({ nodeEnv: "development", env: "dev" });
|
|
|
53
53
|
|
|
54
54
|
Resolves the file chain above relative to `appDirectory`, parses + expands each
|
|
55
55
|
existing file, merges in precedence order, folds the result into `process.env`,
|
|
56
|
-
and returns it. `.json` files (e.g. the `secretsPath`) are parsed as JSON.
|
|
57
|
-
|
|
56
|
+
and returns it. `.json` files (e.g. the `secretsPath`) are parsed as JSON.
|
|
57
|
+
|
|
58
|
+
**`lint` defaults to `false`** — hygiene linting is opt-in. It previously
|
|
59
|
+
defaulted to `true` and therefore ran on every consumer's boot through
|
|
60
|
+
`./preload`, but its output was never correct, so nothing could have correctly
|
|
61
|
+
depended on it. Pass `lint: true` to run the checkers deliberately, or use the
|
|
62
|
+
`config-lint` bin below.
|
|
58
63
|
|
|
59
64
|
```ts
|
|
60
65
|
envs({ appDirectory: __dirname });
|
|
66
|
+
envs({ appDirectory: __dirname, lint: true }); // opt in to hygiene warnings
|
|
61
67
|
```
|
|
62
68
|
|
|
63
69
|
### Lower-level helpers
|
|
64
70
|
|
|
65
|
-
`parse`, `parseJSON`, `config` (from `dotenv-with-expand`), the
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
71
|
+
`parse`, `parseJSON`, `config` (from `dotenv-with-expand`), the hygiene rules,
|
|
72
|
+
`processEnv`, and the merge utilities (`mergeDefaults`, `mergeAssign`,
|
|
73
|
+
`resolveApp`) are all exported from the package root.
|
|
74
|
+
|
|
75
|
+
The hygiene rules come in two groups, mirroring the fixers:
|
|
76
|
+
|
|
77
|
+
| Export | Contents | Takes |
|
|
78
|
+
| --- | --- | --- |
|
|
79
|
+
| `dotenvKeyCheckers` | `incorrectDelimiterChecker`, `leadingCharacterChecker`, `lowercaseKeyChecker` | a key |
|
|
80
|
+
| `dotenvLineCheckers` | `quoteCharacterChecker`, `trailingWhitespaceChecker`, `valueWithoutQuotesChecker` | a raw pre-parse value |
|
|
81
|
+
| `dotenvKeyFixers` / `dotenvLineFixers` | the matching fixers | `(key, value)` |
|
|
82
|
+
|
|
83
|
+
`quoteCharacterChecker` and `valueWithoutQuotesChecker` take
|
|
84
|
+
`(key: string, rawValue: string)` and return a `Finding`
|
|
85
|
+
(`{ key, rule, message }`) rather than logging. `rawValue` must be the value **as
|
|
86
|
+
it literally appears in the file, wrapping quotes intact** — `dotenv.parse`
|
|
87
|
+
strips those quotes, so a parsed value structurally cannot exhibit the defect
|
|
88
|
+
these two exist to detect.
|
|
89
|
+
|
|
90
|
+
> **Deprecated:** the flat `dotenvCheckers` array still exports all six
|
|
91
|
+
> functions and still works, but it cannot express the key/value split above.
|
|
92
|
+
> Prefer `dotenvKeyCheckers` / `dotenvLineCheckers`. `dotenvCheckers` is slated
|
|
93
|
+
> for removal in a future `1.0.0`.
|
|
94
|
+
|
|
95
|
+
## `config-lint`
|
|
96
|
+
|
|
97
|
+
Catches the quote-wrapping mistake at its source: a value copy-pasted verbatim
|
|
98
|
+
out of a shell-quoted `.env` file into a deploy provider's env-var box, where
|
|
99
|
+
the quotes stop being syntax and become part of the secret.
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
config-lint ./apps/web # human output; exit 3 when findings exist
|
|
103
|
+
config-lint ./apps/web --json # the Finding[] array, machine-readable
|
|
104
|
+
config-lint ./apps/web --fix # rewrite fixable single-line entries in place
|
|
105
|
+
config-lint --version # print the installed version and exit
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
It resolves and lints exactly the `.env*` chain `envs()` would load, honoring
|
|
109
|
+
`NODE_ENV` and `ENV`. Exit codes: `0` clean, `1` unexpected error, `2` usage
|
|
110
|
+
error, `3` findings present. No value is ever printed in full — messages mask to
|
|
111
|
+
the last 4 characters. `--version` prints the version read from this package's
|
|
112
|
+
own `package.json` and exits before `<path-to-app-dir>` is required.
|
|
113
|
+
|
|
114
|
+
### Example output
|
|
115
|
+
|
|
116
|
+
Given a `.env` with a quote-wrapped value:
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
FOO='abc123'
|
|
120
|
+
BAR=plain
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Human mode:
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
$ config-lint .
|
|
127
|
+
.env: warning: 'FOO' value ****123' contains quote characters.
|
|
128
|
+
config-lint: 1 finding(s)
|
|
129
|
+
$ echo $?
|
|
130
|
+
3
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`--json` mode:
|
|
134
|
+
|
|
135
|
+
```
|
|
136
|
+
$ config-lint . --json
|
|
137
|
+
[
|
|
138
|
+
{
|
|
139
|
+
"key": "FOO",
|
|
140
|
+
"rule": "quote-character",
|
|
141
|
+
"message": "'FOO' value ****123' contains quote characters.",
|
|
142
|
+
"file": "/path/to/.env"
|
|
143
|
+
}
|
|
144
|
+
]
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`--fix` rewrites the fixable entry in place (the finding above still prints,
|
|
148
|
+
and the exit code still reflects the pre-fix findings — re-run `config-lint`
|
|
149
|
+
to confirm the file is now clean):
|
|
150
|
+
|
|
151
|
+
```
|
|
152
|
+
$ config-lint . --fix
|
|
153
|
+
.env: warning: 'FOO' value ****123' contains quote characters.
|
|
154
|
+
config-lint: 1 finding(s)
|
|
155
|
+
$ cat .env
|
|
156
|
+
FOO=abc123
|
|
157
|
+
BAR=plain
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Known limitations
|
|
161
|
+
|
|
162
|
+
These are disclosed rather than silently inherited:
|
|
163
|
+
|
|
164
|
+
- **`--fix` strips quotes only as one outer matched pair**, and only adds a
|
|
165
|
+
wrapping quote the value does not already contain. A value with an
|
|
166
|
+
unmatched or internal quote (e.g. `O'Brien`) is reported but left
|
|
167
|
+
unchanged. Review every `--fix` diff before committing it.
|
|
168
|
+
- **`--fix` also applies `dotenvKeyFixers` to the key** (e.g. lowercase keys
|
|
169
|
+
are rewritten to uppercase), not just the value fixers above.
|
|
170
|
+
- **`--fix` only rewrites single-line entries.** Multiline quoted values are
|
|
171
|
+
reported but never rewritten.
|
|
172
|
+
- **`trailingWhitespaceChecker` is known-broken and was deliberately left
|
|
173
|
+
unfixed.** It binds its single parameter to whatever the caller passes first,
|
|
174
|
+
and once a value is correlated correctly it essentially cannot fire (`dotenv`
|
|
175
|
+
unconditionally trims unquoted values). It remains in `dotenvLineCheckers` for
|
|
176
|
+
grouping, but its output should not be trusted. Tracked as a follow-up.
|
|
69
177
|
|
|
70
178
|
## Usage
|
|
71
179
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.dotenvCheckers = exports.valueWithoutQuotesChecker = exports.trailingWhitespaceChecker = exports.quoteCharacterChecker = exports.lowercaseKeyChecker = exports.leadingCharacterChecker = exports.incorrectDelimiterChecker = void 0;
|
|
3
|
+
exports.dotenvLineCheckers = exports.dotenvKeyCheckers = exports.dotenvCheckers = exports.valueWithoutQuotesChecker = exports.trailingWhitespaceChecker = exports.quoteCharacterChecker = exports.lowercaseKeyChecker = exports.leadingCharacterChecker = exports.incorrectDelimiterChecker = void 0;
|
|
4
|
+
const redact_js_1 = require("./redact.js");
|
|
4
5
|
const utils_js_1 = require("./utils.js");
|
|
5
6
|
/**
|
|
6
7
|
* Checks if a given key has incorrect delimiters. Delimiters should occur
|
|
@@ -53,22 +54,43 @@ const lowercaseKeyChecker = (key) => {
|
|
|
53
54
|
};
|
|
54
55
|
exports.lowercaseKeyChecker = lowercaseKeyChecker;
|
|
55
56
|
/**
|
|
56
|
-
* Checks
|
|
57
|
-
*
|
|
57
|
+
* Checks whether a value carries quote characters it does not need — the
|
|
58
|
+
* copy-paste-a-shell-quoted-secret-verbatim mistake this package exists to catch
|
|
59
|
+
* at its source.
|
|
58
60
|
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
+
* Skips values whose quoting is load-bearing or whose semantics we cannot judge
|
|
62
|
+
* from the raw text: multiline values, values containing whitespace (where the
|
|
63
|
+
* quotes are what keep the value one token), `${VAR}` expansions, and values
|
|
64
|
+
* containing a `#`.
|
|
65
|
+
*
|
|
66
|
+
* `rawValue` must be the **raw pre-parse** value as captured from the `.env`
|
|
67
|
+
* source — wrapping quotes intact — not the post-`dotenv.parse` value, which has
|
|
68
|
+
* already had its wrapping quotes stripped and so can never exhibit the defect
|
|
69
|
+
* this checker looks for. See `dotenv-correlation.ts` for the contract.
|
|
70
|
+
*
|
|
71
|
+
* @param key - The key the value belongs to.
|
|
72
|
+
* @param rawValue - The raw captured value, quotes intact. `''` for `KEY=`.
|
|
73
|
+
* @returns A {@link Finding} when unnecessary quote characters are found,
|
|
74
|
+
* undefined otherwise.
|
|
61
75
|
*/
|
|
62
|
-
const quoteCharacterChecker = (
|
|
63
|
-
if (
|
|
64
|
-
/[ \t\r\n\f]/.test(
|
|
65
|
-
|
|
66
|
-
|
|
76
|
+
const quoteCharacterChecker = (key, rawValue) => {
|
|
77
|
+
if (rawValue.includes('\n') ||
|
|
78
|
+
/[ \t\r\n\f]/.test(rawValue) ||
|
|
79
|
+
rawValue.includes('$') ||
|
|
80
|
+
rawValue.includes('#')) {
|
|
67
81
|
return;
|
|
68
82
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
83
|
+
// Backtick is a third wrapping quote character dotenv supports
|
|
84
|
+
// (`node_modules/.pnpm/dotenv@16.6.1/node_modules/dotenv/lib/main.js:8`), so a
|
|
85
|
+
// backtick-wrapped secret is the same defect as a `'`- or `"`-wrapped one.
|
|
86
|
+
if (rawValue.includes('"') ||
|
|
87
|
+
rawValue.includes("'") ||
|
|
88
|
+
rawValue.includes('`')) {
|
|
89
|
+
return {
|
|
90
|
+
key,
|
|
91
|
+
rule: 'quote-character',
|
|
92
|
+
message: `'${key}' value ${(0, redact_js_1.maskLast4)(rawValue)} contains quote characters.`,
|
|
93
|
+
};
|
|
72
94
|
}
|
|
73
95
|
};
|
|
74
96
|
exports.quoteCharacterChecker = quoteCharacterChecker;
|
|
@@ -86,23 +108,41 @@ const trailingWhitespaceChecker = (line) => {
|
|
|
86
108
|
};
|
|
87
109
|
exports.trailingWhitespaceChecker = trailingWhitespaceChecker;
|
|
88
110
|
/**
|
|
89
|
-
* Checks
|
|
90
|
-
*
|
|
111
|
+
* Checks whether a value contains whitespace but is not wrapped in quotes, which
|
|
112
|
+
* makes it fragile across shells and dotenv reimplementations.
|
|
91
113
|
*
|
|
92
|
-
* @
|
|
93
|
-
*
|
|
114
|
+
* Like {@link quoteCharacterChecker} this must be fed the raw pre-parse value,
|
|
115
|
+
* quotes intact: `dotenv.parse` strips wrapping quotes, so a correctly quoted
|
|
116
|
+
* multi-word value would look unquoted (and false-positive) after parsing.
|
|
117
|
+
*
|
|
118
|
+
* @param key - The key the value belongs to.
|
|
119
|
+
* @param rawValue - The raw captured value, quotes intact. `''` for `KEY=`.
|
|
120
|
+
* @returns A {@link Finding} when the value has whitespace without wrapping
|
|
121
|
+
* quotes, undefined otherwise.
|
|
94
122
|
*/
|
|
95
|
-
const valueWithoutQuotesChecker = (
|
|
96
|
-
|
|
97
|
-
if (/[ \t\r\n\f]/.test(
|
|
98
|
-
!(
|
|
99
|
-
!(
|
|
100
|
-
|
|
123
|
+
const valueWithoutQuotesChecker = (key, rawValue) => {
|
|
124
|
+
const value = rawValue.trim();
|
|
125
|
+
if (/[ \t\r\n\f]/.test(value) &&
|
|
126
|
+
!(value.startsWith("'") && value.endsWith("'")) &&
|
|
127
|
+
!(value.startsWith('"') && value.endsWith('"')) &&
|
|
128
|
+
// Backtick is a valid dotenv wrapping quote; without this a
|
|
129
|
+
// `TOK=\`multi word\`` line false-positives, and `valueWithoutQuotesFixer`
|
|
130
|
+
// would then re-wrap an already-quoted value.
|
|
131
|
+
!(value.startsWith('`') && value.endsWith('`'))) {
|
|
132
|
+
return {
|
|
133
|
+
key,
|
|
134
|
+
rule: 'value-without-quotes',
|
|
135
|
+
message: `'${key}' value ${(0, redact_js_1.maskLast4)(value)} contains whitespace but is not quoted.`,
|
|
136
|
+
};
|
|
101
137
|
}
|
|
102
138
|
};
|
|
103
139
|
exports.valueWithoutQuotesChecker = valueWithoutQuotesChecker;
|
|
104
140
|
/**
|
|
105
141
|
* An array of functions for checking various aspects of .env file entries.
|
|
142
|
+
*
|
|
143
|
+
* @deprecated Use dotenvKeyCheckers / dotenvLineCheckers instead. Will be
|
|
144
|
+
* removed in a future 1.0.0. The two groupings distinguish checkers that take a
|
|
145
|
+
* key from checkers that take a raw value, which this flat array cannot express.
|
|
106
146
|
*/
|
|
107
147
|
exports.dotenvCheckers = [
|
|
108
148
|
exports.incorrectDelimiterChecker,
|
|
@@ -112,3 +152,25 @@ exports.dotenvCheckers = [
|
|
|
112
152
|
exports.trailingWhitespaceChecker,
|
|
113
153
|
exports.valueWithoutQuotesChecker,
|
|
114
154
|
];
|
|
155
|
+
/**
|
|
156
|
+
* Checkers that take a `.env` **key**. Mirrors `dotenvKeyFixers`.
|
|
157
|
+
*/
|
|
158
|
+
exports.dotenvKeyCheckers = [
|
|
159
|
+
exports.incorrectDelimiterChecker,
|
|
160
|
+
exports.leadingCharacterChecker,
|
|
161
|
+
exports.lowercaseKeyChecker,
|
|
162
|
+
];
|
|
163
|
+
/**
|
|
164
|
+
* Checkers that take a `.env` **value**. Mirrors `dotenvLineFixers`.
|
|
165
|
+
*
|
|
166
|
+
* ⚠️ `trailingWhitespaceChecker` is a known, tracked exception: it was NOT
|
|
167
|
+
* fixed in the pass that corrected the other two, so it still binds its single
|
|
168
|
+
* parameter to whatever the caller passes first and its output should not be
|
|
169
|
+
* trusted. Its membership here reflects the family it belongs to, not a claim
|
|
170
|
+
* that it works. See the README's "Known limitations".
|
|
171
|
+
*/
|
|
172
|
+
exports.dotenvLineCheckers = [
|
|
173
|
+
exports.quoteCharacterChecker,
|
|
174
|
+
exports.trailingWhitespaceChecker,
|
|
175
|
+
exports.valueWithoutQuotesChecker,
|
|
176
|
+
];
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Correlates each key in a raw `.env` file's contents back to the value **as it
|
|
4
|
+
* literally appears in the file**, wrapping quotes intact.
|
|
5
|
+
*
|
|
6
|
+
* Why this module exists: `dotenv.parse` strips wrapping quotes at parse time
|
|
7
|
+
* (`dotenv-with-expand.ts:70`), so a checker fed a parsed value structurally
|
|
8
|
+
* cannot observe the quote-wrapping defect it exists to detect. The checkers
|
|
9
|
+
* need the pre-parse substring, and `dotenv` exports no line splitter to get it
|
|
10
|
+
* (its parser is a single module-private regex).
|
|
11
|
+
*
|
|
12
|
+
* Internal module — deliberately NOT re-exported from `index.ts`.
|
|
13
|
+
*/
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.correlateRawValues = void 0;
|
|
16
|
+
/**
|
|
17
|
+
* Vendored, version-pinned adaptation of `dotenv`'s `LINE` regex.
|
|
18
|
+
*
|
|
19
|
+
* Source: `node_modules/.pnpm/dotenv@16.6.1/node_modules/dotenv/lib/main.js:8`
|
|
20
|
+
* as of `dotenv@16.6.1`. Copied byte-for-byte — the whole point is to split
|
|
21
|
+
* lines exactly the way `dotenv` itself does, so `parse()`'s keys and this
|
|
22
|
+
* module's keys can never disagree.
|
|
23
|
+
*
|
|
24
|
+
* ⚠️ VERSION DRIFT: `package.json` depends on `dotenv` at the caret range
|
|
25
|
+
* `^16.6.1`, so a minor/patch bump can land without a code change here. On any
|
|
26
|
+
* `dotenv` version bump, re-read `lib/main.js`'s `LINE` constant and re-verify
|
|
27
|
+
* this copy against it. See
|
|
28
|
+
* `.omc/plans/2026-09-07-config-lint-prevention-at-source.md` (AC3).
|
|
29
|
+
*
|
|
30
|
+
* Structure, for readers who would rather not parse it by eye:
|
|
31
|
+
* - an optional leading `export ` is consumed *outside* both capture groups
|
|
32
|
+
* - group 1 is the key
|
|
33
|
+
* - group 2 is the value: either a quoted alternative (`'…'`, `"…"`, `` `…` ``,
|
|
34
|
+
* each using a `[^X]` character class that matches `\n`, which is what makes
|
|
35
|
+
* multiline quoted values correlate correctly in a single match) or the
|
|
36
|
+
* unquoted alternative `[^#\r\n]+`, which stops at a `#` and therefore already
|
|
37
|
+
* excludes any inline comment
|
|
38
|
+
* - group 2 is optional, so `KEY=` yields `undefined`
|
|
39
|
+
*/
|
|
40
|
+
const DOTENV_LINE_SOURCE = '(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*\'(?:\\\\\'|[^\'])*\'|\\s*"(?:\\\\"|[^"])*"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)';
|
|
41
|
+
/** A value that is wrapped in a matched pair of `'`, `"`, or `` ` ``. */
|
|
42
|
+
const MATCHED_QUOTE_PAIR = /^(['"`])[\s\S]*\1$/;
|
|
43
|
+
/**
|
|
44
|
+
* Normalize one raw capture into the `rawValue` contract the value checkers
|
|
45
|
+
* expect.
|
|
46
|
+
*
|
|
47
|
+
* - a missing capture (`KEY=`) becomes `''`, mirroring `main.js:25`'s
|
|
48
|
+
* `(match[2] || '')` — never `undefined`, which would throw in the checkers
|
|
49
|
+
* - the leading whitespace the three quoted alternatives each absorb via their
|
|
50
|
+
* own `\s*` is a regex artifact, not part of the value, and is stripped
|
|
51
|
+
* - a quoted value is then returned **exactly as captured, quotes intact**, with
|
|
52
|
+
* no further trimming: the closing quote already bounds it precisely
|
|
53
|
+
* - an unquoted value has any trailing inline comment and the whitespace before
|
|
54
|
+
* it removed, mirroring `main.js:29`'s unconditional `.trim()` of unquoted
|
|
55
|
+
* captures. (The regex's `[^#\r\n]+` alternative already stops at the `#`, so
|
|
56
|
+
* in practice only the trailing whitespace is left to strip; the explicit
|
|
57
|
+
* comment strip below is belt-and-braces and cannot fire on a capture this
|
|
58
|
+
* regex produced.)
|
|
59
|
+
*/
|
|
60
|
+
const normalizeRawValue = (captured) => {
|
|
61
|
+
if (captured === undefined)
|
|
62
|
+
return '';
|
|
63
|
+
const value = captured.trimStart();
|
|
64
|
+
if (MATCHED_QUOTE_PAIR.test(value))
|
|
65
|
+
return value;
|
|
66
|
+
return value.replace(/\s*#[^\n]*$/, '').trimEnd();
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Map every key in `contents` to its raw pre-parse value.
|
|
70
|
+
*
|
|
71
|
+
* Duplicate keys resolve **last-match-wins**, matching `dotenv.parse`'s own
|
|
72
|
+
* behavior (verified: parsing `DUP=first\nDUP=second` returns `{DUP:'second'}`).
|
|
73
|
+
*
|
|
74
|
+
* @param contents - The raw text of a `.env` file.
|
|
75
|
+
* @returns Key → raw value, quotes intact. See {@link normalizeRawValue}.
|
|
76
|
+
*/
|
|
77
|
+
const correlateRawValues = (contents) => {
|
|
78
|
+
// Built per call rather than hoisted: a `g`-flagged regex carries mutable
|
|
79
|
+
// `lastIndex`, and a shared instance would make concurrent or aborted scans
|
|
80
|
+
// silently skip entries.
|
|
81
|
+
const line = new RegExp(DOTENV_LINE_SOURCE, 'mg');
|
|
82
|
+
// Normalize line breaks exactly as `main.js:19` does before matching.
|
|
83
|
+
const normalized = contents.replace(/\r\n?/gm, '\n');
|
|
84
|
+
const rawValues = new Map();
|
|
85
|
+
let match = line.exec(normalized);
|
|
86
|
+
while (match !== null) {
|
|
87
|
+
const key = match[1];
|
|
88
|
+
if (key !== undefined) {
|
|
89
|
+
rawValues.set(key, normalizeRawValue(match[2]));
|
|
90
|
+
}
|
|
91
|
+
match = line.exec(normalized);
|
|
92
|
+
}
|
|
93
|
+
return rawValues;
|
|
94
|
+
};
|
|
95
|
+
exports.correlateRawValues = correlateRawValues;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveDotenvFileChain = void 0;
|
|
4
|
+
const node_path_1 = require("node:path");
|
|
5
|
+
const utils_js_1 = require("./utils.js");
|
|
6
|
+
/**
|
|
7
|
+
* Resolve the canonical layered `.env*` file chain, low → high precedence.
|
|
8
|
+
*
|
|
9
|
+
* Extracted verbatim from `envs.ts` so the `config-lint` bin can lint exactly
|
|
10
|
+
* the files `envs()` would load, without reimplementing the precedence order.
|
|
11
|
+
*
|
|
12
|
+
* Internal module — deliberately NOT re-exported from `index.ts`.
|
|
13
|
+
*
|
|
14
|
+
* @param options.appDirectory - App root. Relative entries resolve against it;
|
|
15
|
+
* when empty the chain is empty, matching `envs()`'s existing behavior.
|
|
16
|
+
* @param options.secretsPath - Optional injected-secrets file, slotted between
|
|
17
|
+
* `.env.${env}` and `.env.${env}.local`.
|
|
18
|
+
* @param options.nodeEnv - `NODE_ENV`. `.env.local` is skipped when `'test'` so
|
|
19
|
+
* personal-machine overrides never leak into a deterministic test run.
|
|
20
|
+
* @param options.env - `ENV`, the stage selector.
|
|
21
|
+
* @returns Absolute paths in precedence order (later wins).
|
|
22
|
+
*/
|
|
23
|
+
const resolveDotenvFileChain = ({ appDirectory = '', secretsPath = '', nodeEnv, env, }) => {
|
|
24
|
+
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
|
|
25
|
+
const dotenvFiles = [
|
|
26
|
+
'.env',
|
|
27
|
+
// Don't include `.env.local` for `test` environment since normally you
|
|
28
|
+
// expect tests to produce the same results for everyone
|
|
29
|
+
nodeEnv !== 'test' && '.env.local',
|
|
30
|
+
env && `.env.${env}`,
|
|
31
|
+
secretsPath,
|
|
32
|
+
env && `.env.${env}.local`,
|
|
33
|
+
].filter(Boolean);
|
|
34
|
+
if (!appDirectory) {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
return dotenvFiles.reduce((acc, dotenvFile) => {
|
|
38
|
+
return (0, node_path_1.isAbsolute)(dotenvFile)
|
|
39
|
+
? acc.concat(dotenvFile)
|
|
40
|
+
: acc.concat((0, utils_js_1.resolveApp)(dotenvFile, appDirectory));
|
|
41
|
+
}, []);
|
|
42
|
+
};
|
|
43
|
+
exports.resolveDotenvFileChain = resolveDotenvFileChain;
|
|
@@ -38,15 +38,17 @@ const lowercaseKeyFixer = (key, line) => {
|
|
|
38
38
|
return [key.toUpperCase(), line];
|
|
39
39
|
};
|
|
40
40
|
exports.lowercaseKeyFixer = lowercaseKeyFixer;
|
|
41
|
-
|
|
42
|
-
//
|
|
43
|
-
//
|
|
41
|
+
const WRAPPING_QUOTES = ["'", '"', '`'];
|
|
42
|
+
// Quote character: strips ONE outer matched pair (`'`, `"` or backtick), the
|
|
43
|
+
// same pair dotenv removes when parsing. A value with an unmatched or internal
|
|
44
|
+
// quote (`O'Brien`) has no safe fix and is left unchanged.
|
|
44
45
|
const quoteCharacterFixer = (key, line) => {
|
|
45
|
-
if (!(0, dotenv_checkers_js_1.quoteCharacterChecker)(line)) {
|
|
46
|
+
if (!(0, dotenv_checkers_js_1.quoteCharacterChecker)(key, line)) {
|
|
46
47
|
return [key, line];
|
|
47
48
|
}
|
|
48
|
-
const
|
|
49
|
-
|
|
49
|
+
const wrapped = line.length >= 2 &&
|
|
50
|
+
WRAPPING_QUOTES.some((q) => line.startsWith(q) && line.endsWith(q));
|
|
51
|
+
return [key, wrapped ? line.slice(1, -1) : line];
|
|
50
52
|
};
|
|
51
53
|
exports.quoteCharacterFixer = quoteCharacterFixer;
|
|
52
54
|
// Fixes trailing whitespace.
|
|
@@ -57,23 +59,18 @@ const trailingWhitespaceFixer = (key, line) => {
|
|
|
57
59
|
return [key, line.trimEnd()];
|
|
58
60
|
};
|
|
59
61
|
exports.trailingWhitespaceFixer = trailingWhitespaceFixer;
|
|
60
|
-
// Value without quotes:
|
|
61
|
-
//
|
|
62
|
+
// Value without quotes: wraps a whitespace-containing unquoted value in a quote
|
|
63
|
+
// character the value does not contain, so dotenv parses it back unchanged.
|
|
64
|
+
// The trimmed value is wrapped because dotenv trims unquoted values. Double
|
|
65
|
+
// quotes are skipped when the value holds a literal `\n`, which dotenv would
|
|
66
|
+
// expand inside them. If no quote is safe, the value is left unchanged.
|
|
62
67
|
const valueWithoutQuotesFixer = (key, line) => {
|
|
63
|
-
if (!(0, dotenv_checkers_js_1.valueWithoutQuotesChecker)(line)) {
|
|
68
|
+
if (!(0, dotenv_checkers_js_1.valueWithoutQuotesChecker)(key, line)) {
|
|
64
69
|
return [key, line];
|
|
65
70
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
else if (line.includes('"')) {
|
|
71
|
-
pureVal = `'${line}'`;
|
|
72
|
-
}
|
|
73
|
-
else {
|
|
74
|
-
pureVal = `'${line}'`;
|
|
75
|
-
}
|
|
76
|
-
return [key, pureVal];
|
|
71
|
+
const value = line.trim();
|
|
72
|
+
const quote = WRAPPING_QUOTES.find((q) => !value.includes(q) && !(q === '"' && value.includes('\\n')));
|
|
73
|
+
return [key, quote ? `${quote}${value}${quote}` : line];
|
|
77
74
|
};
|
|
78
75
|
exports.valueWithoutQuotesFixer = valueWithoutQuotesFixer;
|
|
79
76
|
exports.dotenvKeyFixers = [
|
package/dist/cjs/envs.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.envs = void 0;
|
|
4
4
|
const node_fs_1 = require("node:fs");
|
|
5
|
-
const node_path_1 = require("node:path");
|
|
6
5
|
const dotenv_checkers_js_1 = require("./dotenv-checkers.js");
|
|
6
|
+
const dotenv_correlation_js_1 = require("./dotenv-correlation.js");
|
|
7
|
+
const dotenv_files_js_1 = require("./dotenv-files.js");
|
|
7
8
|
const dotenv_with_expand_js_1 = require("./dotenv-with-expand.js");
|
|
8
9
|
const utils_js_1 = require("./utils.js");
|
|
9
10
|
/**
|
|
@@ -17,48 +18,74 @@ const utils_js_1 = require("./utils.js");
|
|
|
17
18
|
* @param options - Configuration options.
|
|
18
19
|
* @param options.appDirectory - The directory of the app.
|
|
19
20
|
* @param options.secretsPath - The path to an injected secrets file.
|
|
20
|
-
* @param options.lint - Whether to perform linting on the loaded
|
|
21
|
+
* @param options.lint - Whether to perform `.env` hygiene linting on the loaded
|
|
22
|
+
* variables. **Defaults to `false`** — linting is opt-in. It used to default
|
|
23
|
+
* to `true` and ran on every consumer's boot via `./preload`, but its output
|
|
24
|
+
* was never correct (three of six checkers were fed the key where a value was
|
|
25
|
+
* expected, and the two quote checkers were fed post-parse values with the
|
|
26
|
+
* wrapping quotes already stripped, so they structurally could not observe the
|
|
27
|
+
* defect they exist to detect). Nothing could have correctly depended on the
|
|
28
|
+
* old default. Pass `lint: true` to run the checkers deliberately, or use the
|
|
29
|
+
* `config-lint` bin.
|
|
21
30
|
* @param options.override - Whether file values override existing process.env values.
|
|
22
31
|
* @returns An object containing the loaded environment variables.
|
|
23
32
|
*/
|
|
24
|
-
const envs = ({ appDirectory = '', lint =
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const ENV = process.env.ENV;
|
|
28
|
-
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
|
|
29
|
-
const dotenvFiles = [
|
|
30
|
-
'.env',
|
|
31
|
-
// Don't include `.env.local` for `test` environment since normally you
|
|
32
|
-
// expect tests to produce the same results for everyone
|
|
33
|
-
NODE_ENV !== 'test' && '.env.local',
|
|
34
|
-
ENV && `.env.${ENV}`,
|
|
33
|
+
const envs = ({ appDirectory = '', lint = false, secretsPath = '', override = false, } = {}) => {
|
|
34
|
+
const absDotenvFiles = (0, dotenv_files_js_1.resolveDotenvFileChain)({
|
|
35
|
+
appDirectory,
|
|
35
36
|
secretsPath,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
return (0, node_path_1.isAbsolute)(dotenvFile)
|
|
41
|
-
? acc.concat(dotenvFile)
|
|
42
|
-
: acc.concat((0, utils_js_1.resolveApp)(dotenvFile, appDirectory));
|
|
43
|
-
}, []);
|
|
44
|
-
}
|
|
37
|
+
nodeEnv: process.env.NODE_ENV,
|
|
38
|
+
env: process.env.ENV,
|
|
39
|
+
});
|
|
40
|
+
const findings = [];
|
|
45
41
|
const resolvedEnv = absDotenvFiles.reduce((acc, dotenvFile) => {
|
|
46
42
|
if (!(0, node_fs_1.existsSync)(dotenvFile)) {
|
|
47
43
|
return acc;
|
|
48
44
|
}
|
|
49
45
|
const contents = (0, node_fs_1.readFileSync)(dotenvFile, { encoding: 'utf8' });
|
|
50
|
-
const
|
|
46
|
+
const isJson = dotenvFile.endsWith('.json');
|
|
47
|
+
const envs = isJson
|
|
51
48
|
? (0, dotenv_with_expand_js_1.parseJSON)(contents, false, {})
|
|
52
49
|
: (0, dotenv_with_expand_js_1.parse)(contents, false, {});
|
|
53
50
|
if (lint && envs) {
|
|
51
|
+
// Correlate against the `contents` already in scope — no second read.
|
|
52
|
+
// A `.json` secrets file is not dotenv syntax, so the raw-value line
|
|
53
|
+
// checkers do not apply to it; the key checkers still do.
|
|
54
|
+
const rawValues = isJson
|
|
55
|
+
? new Map()
|
|
56
|
+
: (0, dotenv_correlation_js_1.correlateRawValues)(contents);
|
|
54
57
|
Object.entries(envs).forEach(([key, value]) => {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
// Key checkers: unchanged call shape, unchanged `console.log` output.
|
|
59
|
+
(0, dotenv_checkers_js_1.incorrectDelimiterChecker)(key, value);
|
|
60
|
+
(0, dotenv_checkers_js_1.leadingCharacterChecker)(key);
|
|
61
|
+
(0, dotenv_checkers_js_1.lowercaseKeyChecker)(key);
|
|
62
|
+
// UNCHANGED, deliberately. Under the previous uniform
|
|
63
|
+
// `checker(key, value)` call this single-parameter checker bound its
|
|
64
|
+
// `line` parameter to the *key*, never the value. Fixing that is an
|
|
65
|
+
// explicit, documented scope cut (see the plan's v3 changelog and
|
|
66
|
+
// follow-up 1), so its behavior is preserved exactly rather than
|
|
67
|
+
// quietly "improved" — zero regression in either direction.
|
|
68
|
+
(0, dotenv_checkers_js_1.trailingWhitespaceChecker)(key);
|
|
69
|
+
if (isJson) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
// Line checkers: fed the raw pre-parse value, wrapping quotes intact.
|
|
73
|
+
const rawValue = rawValues.get(key) ?? '';
|
|
74
|
+
const quoteFinding = (0, dotenv_checkers_js_1.quoteCharacterChecker)(key, rawValue);
|
|
75
|
+
if (quoteFinding)
|
|
76
|
+
findings.push(quoteFinding);
|
|
77
|
+
const unquotedFinding = (0, dotenv_checkers_js_1.valueWithoutQuotesChecker)(key, rawValue);
|
|
78
|
+
if (unquotedFinding)
|
|
79
|
+
findings.push(unquotedFinding);
|
|
58
80
|
});
|
|
59
81
|
}
|
|
60
82
|
return (0, utils_js_1.mergeAssign)(acc, envs);
|
|
61
83
|
}, {});
|
|
84
|
+
// Sole formatting/printing point for findings. Every message already has its
|
|
85
|
+
// value masked to the last 4 characters by the checker that produced it.
|
|
86
|
+
for (const finding of findings) {
|
|
87
|
+
console.log(`warning: ${finding.message}`);
|
|
88
|
+
}
|
|
62
89
|
return override
|
|
63
90
|
? (0, utils_js_1.mergeAssign)(process.env, resolvedEnv)
|
|
64
91
|
: (0, utils_js_1.mergeDefaults)(process.env, resolvedEnv);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Value masking for lint findings.
|
|
4
|
+
*
|
|
5
|
+
* Local port of `packages/env-doctor/src/redact.ts`'s `maskLast4`, duplicated
|
|
6
|
+
* deliberately rather than imported across packages: `@cogs/config` is the
|
|
7
|
+
* published, dependency-light loader that every app preloads, and
|
|
8
|
+
* `@cogs/env-doctor` is a private tool. A cross-package import would invert that
|
|
9
|
+
* dependency direction for four lines of string slicing.
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.maskLast4 = void 0;
|
|
13
|
+
/**
|
|
14
|
+
* Mask a value to its last 4 characters so a finding can say *which* value it
|
|
15
|
+
* is about without printing a secret in full.
|
|
16
|
+
*
|
|
17
|
+
* Values of 4 characters or fewer are masked outright rather than shown, and an
|
|
18
|
+
* empty value renders as `(empty)` so a `KEY=` line is still legible.
|
|
19
|
+
*/
|
|
20
|
+
const maskLast4 = (value) => {
|
|
21
|
+
if (value.length === 0)
|
|
22
|
+
return '(empty)';
|
|
23
|
+
if (value.length <= 4)
|
|
24
|
+
return '****';
|
|
25
|
+
return `****${value.slice(-4)}`;
|
|
26
|
+
};
|
|
27
|
+
exports.maskLast4 = maskLast4;
|