@cogs/config 0.2.0 → 0.5.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.
- package/README.md +145 -8
- package/dist/cjs/correct-env.js +44 -0
- package/dist/cjs/dotenv-checkers.js +176 -0
- package/dist/cjs/dotenv-correlation.js +95 -0
- package/dist/cjs/dotenv-files.js +43 -0
- package/dist/cjs/dotenv-fixers.js +88 -0
- package/dist/cjs/dotenv-with-expand.js +123 -0
- package/dist/cjs/envs.js +93 -0
- package/dist/cjs/index.js +23 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/preload.js +18 -0
- package/dist/cjs/process-env.js +39 -0
- package/dist/cjs/redact.js +27 -0
- package/dist/cjs/utils.js +65 -0
- package/dist/cli-core.d.ts +72 -0
- package/dist/cli-core.d.ts.map +1 -0
- package/dist/cli-core.js +311 -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/correct-env.d.ts.map +1 -1
- package/dist/correct-env.js.map +1 -1
- package/dist/dotenv-checkers.d.ts +61 -11
- package/dist/dotenv-checkers.d.ts.map +1 -1
- package/dist/dotenv-checkers.js +87 -25
- 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 +7 -7
- package/dist/dotenv-fixers.js.map +1 -1
- package/dist/dotenv-with-expand.d.ts +1 -1
- package/dist/dotenv-with-expand.d.ts.map +1 -1
- package/dist/dotenv-with-expand.js +5 -5
- package/dist/dotenv-with-expand.js.map +1 -1
- package/dist/envs.d.ts +9 -1
- package/dist/envs.d.ts.map +1 -1
- package/dist/envs.js +58 -31
- package/dist/envs.js.map +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/preload.js +3 -3
- package/dist/preload.js.map +1 -1
- package/dist/process-env.d.ts.map +1 -1
- package/dist/process-env.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/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +2 -2
- package/dist/utils.js.map +1 -1
- package/package.json +18 -7
package/README.md
CHANGED
|
@@ -5,8 +5,11 @@ resolves the layered `.env` file chain, expands `${VAR}` references, and folds
|
|
|
5
5
|
the result into `process.env` — with deploy-injected variables staying
|
|
6
6
|
authoritative by default. One loader, one precedence, no per-repo forks.
|
|
7
7
|
|
|
8
|
-
Runtime dependencies: `dotenv`, `dotenv-expand`.
|
|
9
|
-
|
|
8
|
+
Runtime dependencies: `dotenv`, `dotenv-expand`. Ships **dual ESM + CJS** so it
|
|
9
|
+
works from an ESM `--import` preload, a CJS `--require` hook (dd-trace and other
|
|
10
|
+
one-off tools that must load before anything else), and a plain
|
|
11
|
+
`require('@cogs/config')`. Node 20+ (the ESM `--import` preload needs ≥ 20.6;
|
|
12
|
+
the CJS `--require` path works on any Node 20).
|
|
10
13
|
|
|
11
14
|
See [`docs/ENVIRONMENT-CONFIG.md`](../../../next-starters/docs/ENVIRONMENT-CONFIG.md)
|
|
12
15
|
for the full spec and [ADR 0001](../../../next-starters/docs/adr/0001-canonical-env-schema.md)
|
|
@@ -50,19 +53,127 @@ correctEnv({ nodeEnv: "development", env: "dev" });
|
|
|
50
53
|
|
|
51
54
|
Resolves the file chain above relative to `appDirectory`, parses + expands each
|
|
52
55
|
existing file, merges in precedence order, folds the result into `process.env`,
|
|
53
|
-
and returns it. `.json` files (e.g. the `secretsPath`) are parsed as JSON.
|
|
54
|
-
|
|
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.
|
|
55
63
|
|
|
56
64
|
```ts
|
|
57
65
|
envs({ appDirectory: __dirname });
|
|
66
|
+
envs({ appDirectory: __dirname, lint: true }); // opt in to hygiene warnings
|
|
58
67
|
```
|
|
59
68
|
|
|
60
69
|
### Lower-level helpers
|
|
61
70
|
|
|
62
|
-
`parse`, `parseJSON`, `config` (from `dotenv-with-expand`), the
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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` can corrupt a value containing an internal quote.**
|
|
165
|
+
`quoteCharacterFixer` and `valueWithoutQuotesFixer` strip and add quotes
|
|
166
|
+
*globally* rather than as a matched pair. Fixing those fixers is tracked
|
|
167
|
+
separately; 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.
|
|
66
177
|
|
|
67
178
|
## Usage
|
|
68
179
|
|
|
@@ -85,6 +196,32 @@ The `./preload` entry side-effect-calls `correctEnv()` then
|
|
|
85
196
|
`SECRETS_PATH` (`${SECRETS_PATH}secrets.json`, or `''` when unset). Requires
|
|
86
197
|
Node ≥ 20.6.
|
|
87
198
|
|
|
199
|
+
### CJS preload (`--require`) — dd-trace and one-off tools
|
|
200
|
+
|
|
201
|
+
For a CJS `--require` hook (or an app `server-preload.cjs`), use the `./register`
|
|
202
|
+
subpath — same side effect, loaded via CommonJS so it can sit alongside
|
|
203
|
+
`dd-trace/init` and other tools that must run before the app:
|
|
204
|
+
|
|
205
|
+
```jsonc
|
|
206
|
+
// package.json — order matters: env first, then tracer
|
|
207
|
+
{
|
|
208
|
+
"scripts": {
|
|
209
|
+
"start": "NODE_OPTIONS=\"--require @cogs/config/register --require dd-trace/init\" node server.js"
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Or from a `server-preload.cjs` that also does other CJS bootstrap:
|
|
215
|
+
|
|
216
|
+
```cjs
|
|
217
|
+
// server-preload.cjs
|
|
218
|
+
require("@cogs/config/register"); // folds the .env chain into process.env
|
|
219
|
+
require("dd-trace").init();
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`require('@cogs/config')` also exposes the full API (`correctEnv`, `envs`, …)
|
|
223
|
+
from the CJS build for scripts that need to call the loader directly.
|
|
224
|
+
|
|
88
225
|
### `next.config.ts` (build time)
|
|
89
226
|
|
|
90
227
|
Load env at the top of the config so the build sees resolved values:
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.correctEnv = void 0;
|
|
4
|
+
// please note that `process.env` is not exported so only this process has the
|
|
5
|
+
// values for anything set in `process.env`
|
|
6
|
+
function existy(x) {
|
|
7
|
+
return x != null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Corrects and sets various environment variables based on provided values or
|
|
11
|
+
* defaults. Do this as the first thing so that any code reading it knows the
|
|
12
|
+
* right env. Existing `process.env` values always win over the provided options.
|
|
13
|
+
*
|
|
14
|
+
* @param options - An optional object containing environment-related options.
|
|
15
|
+
* @param options.nodeEnv - The desired Node.js environment (NODE_ENV).
|
|
16
|
+
* @param options.babelEnv - The desired Babel environment (BABEL_ENV).
|
|
17
|
+
* @param options.browserslistEnv - The desired Browserslist environment (BROWSERSLIST_ENV).
|
|
18
|
+
* @param options.env - The desired environment (ENV).
|
|
19
|
+
* @param options.browser - The desired browser environment (__BROWSER__).
|
|
20
|
+
*/
|
|
21
|
+
const correctEnv = ({ nodeEnv, babelEnv, browserslistEnv, env, browser, } = {}) => {
|
|
22
|
+
const nEnv = process.env.NODE_ENV || nodeEnv;
|
|
23
|
+
const bEnv = process.env.BABEL_ENV || babelEnv;
|
|
24
|
+
const blEnv = process.env.BROWSERSLIST_ENV || browserslistEnv || nEnv;
|
|
25
|
+
const aEnv = process.env.ENV || env;
|
|
26
|
+
let browserEnv = process.env.__BROWSER__;
|
|
27
|
+
if (!existy(browserEnv) && existy(browser)) {
|
|
28
|
+
browserEnv = browser;
|
|
29
|
+
}
|
|
30
|
+
if (existy(bEnv)) {
|
|
31
|
+
process.env.BABEL_ENV = bEnv;
|
|
32
|
+
}
|
|
33
|
+
if (existy(aEnv)) {
|
|
34
|
+
process.env.ENV = aEnv;
|
|
35
|
+
}
|
|
36
|
+
if (existy(blEnv)) {
|
|
37
|
+
process.env.BROWSERSLIST_ENV = blEnv;
|
|
38
|
+
}
|
|
39
|
+
if (existy(browserEnv)) {
|
|
40
|
+
process.env.__BROWSER__ = browserEnv;
|
|
41
|
+
}
|
|
42
|
+
process.env = Object.assign(process.env, { NODE_ENV: nEnv });
|
|
43
|
+
};
|
|
44
|
+
exports.correctEnv = correctEnv;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
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");
|
|
5
|
+
const utils_js_1 = require("./utils.js");
|
|
6
|
+
/**
|
|
7
|
+
* Checks if a given key has incorrect delimiters. Delimiters should occur
|
|
8
|
+
* between characters, not as the initial character. This function removes
|
|
9
|
+
* any invalid leading characters before checking for incorrect delimiters.
|
|
10
|
+
*
|
|
11
|
+
* @param key - The key to be checked for incorrect delimiters.
|
|
12
|
+
* @param line - The line of text where the key is found (for logging purposes).
|
|
13
|
+
* @returns True if incorrect delimiters are found, undefined otherwise.
|
|
14
|
+
*/
|
|
15
|
+
const incorrectDelimiterChecker = (key, line) => {
|
|
16
|
+
// delimiters occur /between/ characters, not as the initial character, so
|
|
17
|
+
// we should remove all invalid leading characters before checking for
|
|
18
|
+
// incorrect delimiters
|
|
19
|
+
const cleanedKey = (0, utils_js_1.removeInvalidLeadingChars)(key);
|
|
20
|
+
const chars = cleanedKey.trim().split('');
|
|
21
|
+
if (chars.some((char) => !/[a-z0-9_]/i.test(char))) {
|
|
22
|
+
console.log(`warning: '${key}' incorrect delimiter`);
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
exports.incorrectDelimiterChecker = incorrectDelimiterChecker;
|
|
27
|
+
/**
|
|
28
|
+
* Checks if a key starts with an unallowed character. Only characters from A to
|
|
29
|
+
* Z and _(underscore) are allowed as the initial character.
|
|
30
|
+
*
|
|
31
|
+
* @param key - The key to be checked for an unallowed leading character.
|
|
32
|
+
* @returns True if an unallowed leading character is found, undefined otherwise.
|
|
33
|
+
*/
|
|
34
|
+
const leadingCharacterChecker = (key) => {
|
|
35
|
+
if (/^[a-z_]/i.test(key)) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
console.log(`warning: '${key}' starts with an unallowed character. (characters from A to Z and _(underscore) are allowed)`);
|
|
39
|
+
return true;
|
|
40
|
+
};
|
|
41
|
+
exports.leadingCharacterChecker = leadingCharacterChecker;
|
|
42
|
+
/**
|
|
43
|
+
* Checks if a key contains lowercase characters.
|
|
44
|
+
*
|
|
45
|
+
* @param key - The key to be checked for lowercase characters.
|
|
46
|
+
* @returns True if lowercase characters are found in the key, undefined otherwise.
|
|
47
|
+
*/
|
|
48
|
+
const lowercaseKeyChecker = (key) => {
|
|
49
|
+
if (key.toUpperCase() === key) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
console.log(`warning: '${key}' has lowercase characters.`);
|
|
53
|
+
return true;
|
|
54
|
+
};
|
|
55
|
+
exports.lowercaseKeyChecker = lowercaseKeyChecker;
|
|
56
|
+
/**
|
|
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.
|
|
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.
|
|
75
|
+
*/
|
|
76
|
+
const quoteCharacterChecker = (key, rawValue) => {
|
|
77
|
+
if (rawValue.includes('\n') ||
|
|
78
|
+
/[ \t\r\n\f]/.test(rawValue) ||
|
|
79
|
+
rawValue.includes('$') ||
|
|
80
|
+
rawValue.includes('#')) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
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
|
+
};
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
exports.quoteCharacterChecker = quoteCharacterChecker;
|
|
97
|
+
/**
|
|
98
|
+
* Checks if a line has trailing whitespace characters (spaces or tabs).
|
|
99
|
+
*
|
|
100
|
+
* @param line - The line to be checked for trailing whitespace.
|
|
101
|
+
* @returns True if trailing whitespace is found in the line, undefined otherwise.
|
|
102
|
+
*/
|
|
103
|
+
const trailingWhitespaceChecker = (line) => {
|
|
104
|
+
if (line.endsWith(' ')) {
|
|
105
|
+
console.log(`warning: '${line}' has a trailing whitespace.`);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
exports.trailingWhitespaceChecker = trailingWhitespaceChecker;
|
|
110
|
+
/**
|
|
111
|
+
* Checks whether a value contains whitespace but is not wrapped in quotes, which
|
|
112
|
+
* makes it fragile across shells and dotenv reimplementations.
|
|
113
|
+
*
|
|
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.
|
|
122
|
+
*/
|
|
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
|
+
};
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
exports.valueWithoutQuotesChecker = valueWithoutQuotesChecker;
|
|
140
|
+
/**
|
|
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.
|
|
146
|
+
*/
|
|
147
|
+
exports.dotenvCheckers = [
|
|
148
|
+
exports.incorrectDelimiterChecker,
|
|
149
|
+
exports.leadingCharacterChecker,
|
|
150
|
+
exports.lowercaseKeyChecker,
|
|
151
|
+
exports.quoteCharacterChecker,
|
|
152
|
+
exports.trailingWhitespaceChecker,
|
|
153
|
+
exports.valueWithoutQuotesChecker,
|
|
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;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dotenvLineFixers = exports.dotenvKeyFixers = exports.valueWithoutQuotesFixer = exports.trailingWhitespaceFixer = exports.quoteCharacterFixer = exports.lowercaseKeyFixer = exports.leadingCharacterFixer = exports.incorrectDelimiterFixer = void 0;
|
|
4
|
+
const dotenv_checkers_js_1 = require("./dotenv-checkers.js");
|
|
5
|
+
const utils_js_1 = require("./utils.js");
|
|
6
|
+
/**
|
|
7
|
+
* Fixes incorrect delimiters by replacing non-alphanumeric characters with
|
|
8
|
+
* underscores ('_'). Also ensures that an underscore separates words in the key.
|
|
9
|
+
*
|
|
10
|
+
* @param key - The key to fix.
|
|
11
|
+
* @param line - The corresponding line from the .env file.
|
|
12
|
+
* @returns An array containing the fixed key and the original line.
|
|
13
|
+
*/
|
|
14
|
+
const incorrectDelimiterFixer = (key, line) => {
|
|
15
|
+
if (!(0, dotenv_checkers_js_1.incorrectDelimiterChecker)(key, line)) {
|
|
16
|
+
return [key, line];
|
|
17
|
+
}
|
|
18
|
+
let cleanedKey = (0, utils_js_1.removeInvalidLeadingChars)(key);
|
|
19
|
+
const startIdx = key.length - cleanedKey.length;
|
|
20
|
+
cleanedKey = key.slice(startIdx).replace(/[^a-z0-9]/gi, '_');
|
|
21
|
+
return [`${key.substring(0, startIdx)}${cleanedKey}`, line];
|
|
22
|
+
};
|
|
23
|
+
exports.incorrectDelimiterFixer = incorrectDelimiterFixer;
|
|
24
|
+
// Fixes key that starts with an unallowed character.
|
|
25
|
+
const leadingCharacterFixer = (key, line) => {
|
|
26
|
+
if (!(0, dotenv_checkers_js_1.leadingCharacterChecker)(key)) {
|
|
27
|
+
return [key, line];
|
|
28
|
+
}
|
|
29
|
+
const cleanedKey = (0, utils_js_1.removeInvalidLeadingChars)(key);
|
|
30
|
+
return [cleanedKey, line];
|
|
31
|
+
};
|
|
32
|
+
exports.leadingCharacterFixer = leadingCharacterFixer;
|
|
33
|
+
// Fixes lowercase key by upper casing it.
|
|
34
|
+
const lowercaseKeyFixer = (key, line) => {
|
|
35
|
+
if (!(0, dotenv_checkers_js_1.lowercaseKeyChecker)(key)) {
|
|
36
|
+
return [key, line];
|
|
37
|
+
}
|
|
38
|
+
return [key.toUpperCase(), line];
|
|
39
|
+
};
|
|
40
|
+
exports.lowercaseKeyFixer = lowercaseKeyFixer;
|
|
41
|
+
// Quote character: Fixes when a value contains quote characters(`'` / `"`) but
|
|
42
|
+
// skips if the value is multiline, contains whitespaces, newline characters or
|
|
43
|
+
// hash signs:
|
|
44
|
+
const quoteCharacterFixer = (key, line) => {
|
|
45
|
+
if (!(0, dotenv_checkers_js_1.quoteCharacterChecker)(key, line)) {
|
|
46
|
+
return [key, line];
|
|
47
|
+
}
|
|
48
|
+
const pureVal = line.replace(/"|'/g, '');
|
|
49
|
+
return [key, pureVal];
|
|
50
|
+
};
|
|
51
|
+
exports.quoteCharacterFixer = quoteCharacterFixer;
|
|
52
|
+
// Fixes trailing whitespace.
|
|
53
|
+
const trailingWhitespaceFixer = (key, line) => {
|
|
54
|
+
if (!(0, dotenv_checkers_js_1.trailingWhitespaceChecker)(line)) {
|
|
55
|
+
return [key, line];
|
|
56
|
+
}
|
|
57
|
+
return [key, line.trimEnd()];
|
|
58
|
+
};
|
|
59
|
+
exports.trailingWhitespaceFixer = trailingWhitespaceFixer;
|
|
60
|
+
// Value without quotes: Detects if a value contains whitespaces and at the
|
|
61
|
+
// same time doesn't contain quote characters (`'` / `"`):
|
|
62
|
+
const valueWithoutQuotesFixer = (key, line) => {
|
|
63
|
+
if (!(0, dotenv_checkers_js_1.valueWithoutQuotesChecker)(key, line)) {
|
|
64
|
+
return [key, line];
|
|
65
|
+
}
|
|
66
|
+
let pureVal = '';
|
|
67
|
+
if (line.includes("'")) {
|
|
68
|
+
pureVal = `"${line}"`;
|
|
69
|
+
}
|
|
70
|
+
else if (line.includes('"')) {
|
|
71
|
+
pureVal = `'${line}'`;
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
pureVal = `'${line}'`;
|
|
75
|
+
}
|
|
76
|
+
return [key, pureVal];
|
|
77
|
+
};
|
|
78
|
+
exports.valueWithoutQuotesFixer = valueWithoutQuotesFixer;
|
|
79
|
+
exports.dotenvKeyFixers = [
|
|
80
|
+
exports.incorrectDelimiterFixer,
|
|
81
|
+
exports.leadingCharacterFixer,
|
|
82
|
+
exports.lowercaseKeyFixer,
|
|
83
|
+
];
|
|
84
|
+
exports.dotenvLineFixers = [
|
|
85
|
+
exports.quoteCharacterFixer,
|
|
86
|
+
exports.trailingWhitespaceFixer,
|
|
87
|
+
exports.valueWithoutQuotesFixer,
|
|
88
|
+
];
|