@pavol-baker/envaudit 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +245 -3
- package/bin/envaudit.js +4 -0
- package/package.json +46 -4
- package/src/analyze.js +215 -0
- package/src/cli.js +187 -0
- package/src/config.js +110 -0
- package/src/dotenv.js +80 -0
- package/src/extractors.js +295 -0
- package/src/glob.js +59 -0
- package/src/index.js +6 -0
- package/src/report.js +168 -0
- package/src/scan.js +102 -0
- package/src/secrets.js +27 -0
- package/src/sync.js +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 envaudit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,245 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# envaudit
|
|
2
|
+
|
|
3
|
+
**Catch environment variable drift before it breaks prod.**
|
|
4
|
+
|
|
5
|
+
You add `process.env.STRIPE_SECRET_KEY` to your code, ship it, and forget to add it to `.env.example`.
|
|
6
|
+
Two weeks later a teammate pulls main, the app crashes, and they lose an hour asking around for "the env var thing".
|
|
7
|
+
Or the deploy fails because nobody set the variable in staging.
|
|
8
|
+
|
|
9
|
+
`envaudit` reads your code, works out which environment variables it actually uses, and checks them against your `.env.example`:
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
$ npx @pavol-baker/envaudit
|
|
13
|
+
|
|
14
|
+
envaudit · 5 source files scanned
|
|
15
|
+
|
|
16
|
+
.env.example · 6 variables documented
|
|
17
|
+
✖ Looks like a real secret in an example file (rotate it!)
|
|
18
|
+
STRIPE_SECRET_KEY .env.example:10 Stripe live key
|
|
19
|
+
⚠ .env is not in .gitignore — one `git add .` away from leaking secrets
|
|
20
|
+
✖ Undocumented (5) — used in code, missing from .env.example
|
|
21
|
+
REDIS_URL worker/queue.py:2:25
|
|
22
|
+
REDIS_VERSION docker-compose.yml:3:20
|
|
23
|
+
SMTP_HOST src/lib/mail.ts:2:21
|
|
24
|
+
SMTP_PASSWORD src/lib/mail.ts:3:59
|
|
25
|
+
SMTP_USER src/lib/mail.ts:3:29
|
|
26
|
+
⚠ Unused (1) — documented but never referenced
|
|
27
|
+
LEGACY_SESSION_KEY .env.example:7
|
|
28
|
+
ℹ Missing from your .env (3) — your app may crash locally
|
|
29
|
+
JWT_SECRET, LEGACY_SESSION_KEY, STRIPE_SECRET_KEY
|
|
30
|
+
|
|
31
|
+
✖ 6 errors, 2 warnings
|
|
32
|
+
→ run npx @pavol-baker/envaudit sync to add the missing keys to your example file
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Then `npx @pavol-baker/envaudit sync` fixes the example file for you.
|
|
36
|
+
|
|
37
|
+
- **Zero dependencies.** One `npx` and it runs. Nothing to install, nothing to configure.
|
|
38
|
+
- **Polyglot.** JS/TS, Python, Go, Rust, Ruby, PHP, Java/Kotlin, C#, Elixir, Swift, Dart, Prisma, Docker Compose, Spring.
|
|
39
|
+
- **Monorepo-aware.** Each `apps/*/.env.example` covers its own subtree.
|
|
40
|
+
- **CI-ready.** Non-zero exit code, JSON output, and inline GitHub PR annotations.
|
|
41
|
+
- **Safety checks.** Finds real secrets pasted into example files, and `.env` files that are committed or missing from `.gitignore`.
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npx @pavol-baker/envaudit # audit the current directory
|
|
47
|
+
npx @pavol-baker/envaudit sync # add undocumented vars to .env.example
|
|
48
|
+
npx @pavol-baker/envaudit list # inventory: every env var the code reads, and where
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or install it in your project, then use the short `envaudit` command in npm scripts:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
npm install --save-dev @pavol-baker/envaudit
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{ "scripts": { "env:check": "envaudit", "env:sync": "envaudit sync" } }
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Requires Node.js 18 or newer, but the project you audit can be written in any of the languages below.
|
|
62
|
+
|
|
63
|
+
## What it checks
|
|
64
|
+
|
|
65
|
+
| Check | Severity | What it means |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| **Undocumented** | error | The code reads it but `.env.example` doesn't list it. A new teammate or a fresh deploy will be missing it. |
|
|
68
|
+
| **Secret in example file** | error | A value in `.env.example` looks like a real credential (Stripe live key, AWS key, GitHub token, private key, connection string with a password...). |
|
|
69
|
+
| **Committed `.env`** | error | Your real `.env` is tracked by git. |
|
|
70
|
+
| **Unused** | warning | `.env.example` lists it, but nothing reads it anymore. |
|
|
71
|
+
| **Duplicate key** | warning | The same key is defined twice in the example. The last one silently wins. |
|
|
72
|
+
| **`.env` not ignored** | warning | `.env` exists and isn't in `.gitignore`. |
|
|
73
|
+
| **Missing locally** | info | `.env.example` lists it but your local `.env` doesn't. This explains "works on their machine". |
|
|
74
|
+
|
|
75
|
+
The exit code is `1` when there are errors, or warnings too with `--strict`. Otherwise it's `0`.
|
|
76
|
+
|
|
77
|
+
### Fewer false positives
|
|
78
|
+
|
|
79
|
+
- **Commented-out code is skipped**, and the lexer knows about strings, so `"http://..."` doesn't count as a comment.
|
|
80
|
+
- **Well-known variables are ignored**: `NODE_ENV`, `PATH`, `HOME`, `CI`, `GITHUB_SHA`, Vite's `MODE`/`DEV`/`PROD`, and so on. Turn this off with `--no-builtins`.
|
|
81
|
+
- **"Unused" is cautious.** If a variable is mentioned anywhere in the repo (a Dockerfile, a shell script, a CI workflow, `next.config.js`), it doesn't count as unused, even when no code reads it directly.
|
|
82
|
+
- **Optional variables** can be documented commented out (`# SENTRY_DSN=`). They count as documented, but nobody is told they're missing from their `.env`.
|
|
83
|
+
- **Writes aren't reads.** `process.env.FOO = "x"` is not reported.
|
|
84
|
+
|
|
85
|
+
## Supported languages
|
|
86
|
+
|
|
87
|
+
| Language | Detected patterns |
|
|
88
|
+
|---|---|
|
|
89
|
+
| JavaScript / TypeScript (also `.vue`, `.svelte`, `.astro`) | `process.env.X`, `process.env["X"]`, `const { X, Y = 1 } = process.env`, `import.meta.env.X`, `Bun.env.X`, `Deno.env.get("X")`, SvelteKit `import { X } from '$env/static/private'` |
|
|
90
|
+
| Python | `os.environ["X"]`, `os.environ.get("X")`, `os.getenv("X")`, `environ["X"]` |
|
|
91
|
+
| Go | `os.Getenv("X")`, `os.LookupEnv("X")` |
|
|
92
|
+
| Rust | `env::var("X")`, `std::env::var_os("X")`, `env!("X")`, `option_env!("X")`, `dotenvy::var("X")` |
|
|
93
|
+
| Ruby | `ENV["X"]`, `ENV.fetch("X")`, `ENV.key?("X")` |
|
|
94
|
+
| PHP / Laravel | `getenv('X')`, `$_ENV['X']`, `env('X')` |
|
|
95
|
+
| Java / Kotlin / Scala / Groovy | `System.getenv("X")` |
|
|
96
|
+
| Spring (`.properties`, `application*.yml`) | `${X}`, `${X:default}` (UPPER_CASE names only) |
|
|
97
|
+
| C# / F# | `Environment.GetEnvironmentVariable("X")` |
|
|
98
|
+
| Elixir | `System.get_env("X")`, `System.fetch_env!("X")` |
|
|
99
|
+
| Swift | `ProcessInfo.processInfo.environment["X"]` |
|
|
100
|
+
| Dart / Flutter | `Platform.environment['X']`, `String.fromEnvironment('X')` |
|
|
101
|
+
| Prisma | `env("DATABASE_URL")` |
|
|
102
|
+
| Docker Compose | `${X}`, `${X:-default}`, `${X:?err}`, `$X` |
|
|
103
|
+
|
|
104
|
+
Is a pattern you use missing? Adding a language takes about five lines in [`src/extractors.js`](src/extractors.js). PRs are welcome.
|
|
105
|
+
|
|
106
|
+
## Monorepos
|
|
107
|
+
|
|
108
|
+
envaudit finds every example file (`.env.example`, `.env.sample`, `.env.template`, `.env.dist`) and makes each one responsible for the files below it:
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
.env.example ← documents SHARED_SECRET
|
|
112
|
+
apps/web/.env.example ← documents NEXT_PUBLIC_URL
|
|
113
|
+
apps/web/src/page.tsx → checked against apps/web + root (inherited)
|
|
114
|
+
apps/api/.env.example
|
|
115
|
+
apps/api/main.go → checked against apps/api + root
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
A variable documented in a parent example also counts as documented for its children. To use a single example file instead, pass `--example path/to/file`.
|
|
119
|
+
|
|
120
|
+
## Use it in CI
|
|
121
|
+
|
|
122
|
+
### GitHub Actions
|
|
123
|
+
|
|
124
|
+
```yaml
|
|
125
|
+
# .github/workflows/env.yml
|
|
126
|
+
name: env
|
|
127
|
+
on: [pull_request]
|
|
128
|
+
jobs:
|
|
129
|
+
envaudit:
|
|
130
|
+
runs-on: ubuntu-latest
|
|
131
|
+
steps:
|
|
132
|
+
- uses: actions/checkout@v4
|
|
133
|
+
- uses: actions/setup-node@v4
|
|
134
|
+
with: { node-version: 22 }
|
|
135
|
+
- run: npx @pavol-baker/envaudit
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
On GitHub Actions, envaudit detects the environment and adds **inline annotations to the PR diff** on the exact line that uses an undocumented variable.
|
|
139
|
+
|
|
140
|
+
You can also use the bundled action:
|
|
141
|
+
|
|
142
|
+
```yaml
|
|
143
|
+
- uses: pavol-baker/envaudit@v0
|
|
144
|
+
with:
|
|
145
|
+
args: --strict
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Any other CI
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
npx @pavol-baker/envaudit --format json > envaudit.json # machine-readable
|
|
152
|
+
npx @pavol-baker/envaudit --strict # also fail on stale variables
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### pre-commit
|
|
156
|
+
|
|
157
|
+
```yaml
|
|
158
|
+
# .pre-commit-config.yaml
|
|
159
|
+
repos:
|
|
160
|
+
- repo: https://github.com/pavol-baker/envaudit
|
|
161
|
+
rev: v0.1.0
|
|
162
|
+
hooks:
|
|
163
|
+
- id: envaudit
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Or with husky / lefthook, just run `npx @pavol-baker/envaudit`.
|
|
167
|
+
|
|
168
|
+
## Commands and options
|
|
169
|
+
|
|
170
|
+
```
|
|
171
|
+
envaudit [check] [dir] Audit code against .env.example (default command)
|
|
172
|
+
envaudit sync [dir] Add undocumented variables to .env.example
|
|
173
|
+
envaudit list [dir] List every env var the code reads, and where
|
|
174
|
+
|
|
175
|
+
-e, --example <file> Use this example file (disables monorepo detection)
|
|
176
|
+
--env <file> Local env file to compare against (default: .env)
|
|
177
|
+
--strict Also fail on unused / duplicate variables
|
|
178
|
+
--ignore-var <names> Never report these vars (comma-separated, globs ok: AWS_*)
|
|
179
|
+
--no-builtins Also report OS/CI/framework vars like NODE_ENV, CI, HOME
|
|
180
|
+
-f, --format <fmt> pretty | json | github (auto: github on GitHub Actions)
|
|
181
|
+
--json Shortcut for --format json
|
|
182
|
+
-v, --verbose Show every location, not just the first two
|
|
183
|
+
--prune (sync) also remove unused variables
|
|
184
|
+
--dry-run (sync) show what would change without writing
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
`sync` appends each missing variable with a pointer to where it's used, so reviewers get context:
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
# used in src/lib/mail.ts:2
|
|
191
|
+
SMTP_HOST=
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Configuration
|
|
195
|
+
|
|
196
|
+
Most projects need no config at all. If you do need it, create `envaudit.config.json` (or add an `"envaudit"` key to `package.json`):
|
|
197
|
+
|
|
198
|
+
```jsonc
|
|
199
|
+
{
|
|
200
|
+
// never report these (globs allowed)
|
|
201
|
+
"ignoreVars": ["AWS_*", "FEATURE_FLAG_*"],
|
|
202
|
+
// documented vars that libraries read on their own (the AWS SDK, Prisma...)
|
|
203
|
+
"ignoreUnused": ["AWS_REGION", "DATABASE_URL"],
|
|
204
|
+
// extra paths to skip (.gitignore is already respected)
|
|
205
|
+
"ignore": ["scripts/legacy/**", "**/*.stories.tsx"],
|
|
206
|
+
"strict": false
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
To silence a single line:
|
|
211
|
+
|
|
212
|
+
```js
|
|
213
|
+
const x = process.env.SOMETHING_WEIRD; // envaudit-ignore
|
|
214
|
+
|
|
215
|
+
// envaudit-ignore-next-line
|
|
216
|
+
const y = process.env.ANOTHER_ONE;
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## Programmatic API
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
import { audit, planSync, formatPretty } from '@pavol-baker/envaudit';
|
|
223
|
+
|
|
224
|
+
const result = audit('./my-project', { strict: true });
|
|
225
|
+
console.log(result.ok, result.counts);
|
|
226
|
+
console.log(formatPretty(result));
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## How it works and limitations
|
|
230
|
+
|
|
231
|
+
envaudit uses fast, language-aware pattern matching, not a full parser for every language. That keeps it dependency-free and quick (thousands of files per second), but it has limits:
|
|
232
|
+
|
|
233
|
+
- **Dynamic access isn't resolved**: in `process.env[name]` and `os.getenv(f"{prefix}_KEY")`, envaudit can't know the name.
|
|
234
|
+
- **Variables read by libraries** (the AWS SDK reading `AWS_REGION`, for example) never appear in your code. If you document them, list them under `ignoreUnused` so they aren't reported as unused.
|
|
235
|
+
- **Config-schema libraries** (`envalid`, `t3-env`, `pydantic-settings`) declare variables in their own way. If you validate env with zod, e.g. `z.object({ API_KEY: ... })`, write `process.env.API_KEY` in the `runtimeEnv` mapping (as t3-env recommends) and envaudit picks it up.
|
|
236
|
+
|
|
237
|
+
Files are listed with `git ls-files`, so your `.gitignore` is respected. Outside a git repo, envaudit walks the directory and skips the usual suspects (`node_modules`, `dist`, `.venv`, `target`, ...).
|
|
238
|
+
|
|
239
|
+
## Contributing
|
|
240
|
+
|
|
241
|
+
Bug reports with a small reproduction are gold. See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
242
|
+
|
|
243
|
+
## License
|
|
244
|
+
|
|
245
|
+
[MIT](LICENSE)
|
package/bin/envaudit.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pavol-baker/envaudit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Catch env var drift before it breaks prod. Finds environment variables your code uses but .env.example forgets, and the other way round. Zero dependencies, 12+ languages, monorepo-aware, CI-ready.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/pavol-baker/envaudit.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/pavol-baker/envaudit#readme",
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/pavol-baker/envaudit/issues"
|
|
12
|
+
},
|
|
13
|
+
"type": "module",
|
|
14
|
+
"bin": {
|
|
15
|
+
"envaudit": "bin/envaudit.js"
|
|
16
|
+
},
|
|
17
|
+
"main": "src/index.js",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"bin",
|
|
23
|
+
"src",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "node --test \"test/*.test.js\"",
|
|
29
|
+
"selfcheck": "node bin/envaudit.js"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=18"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"env",
|
|
36
|
+
"dotenv",
|
|
37
|
+
".env",
|
|
38
|
+
".env.example",
|
|
39
|
+
"environment-variables",
|
|
40
|
+
"lint",
|
|
41
|
+
"cli",
|
|
42
|
+
"ci",
|
|
43
|
+
"devtools",
|
|
44
|
+
"config",
|
|
45
|
+
"monorepo"
|
|
46
|
+
],
|
|
47
|
+
"license": "MIT"
|
|
48
|
+
}
|
package/src/analyze.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join, posix, resolve } from 'node:path';
|
|
3
|
+
import { BUILTIN_VARS, loadConfig, nameMatcher } from './config.js';
|
|
4
|
+
import { parseDotenv, findDuplicates } from './dotenv.js';
|
|
5
|
+
import { extract, languageFor } from './extractors.js';
|
|
6
|
+
import { listFiles, readText, gitStatusOf } from './scan.js';
|
|
7
|
+
import { detectSecret } from './secrets.js';
|
|
8
|
+
|
|
9
|
+
const EXAMPLE_FILE = /^(?:\.env(?:\.[\w-]+)*\.(?:example|sample|template|dist)|(?:example|sample)\.env)$/i;
|
|
10
|
+
const EXAMPLE_PRIORITY = ['.env.example', '.env.sample', '.env.template', '.env.dist'];
|
|
11
|
+
const ENV_LIKE = /(^|\/)\.env(\.[\w.-]+)?$|\.env$/i;
|
|
12
|
+
const PROSE = /\.(md|mdx|markdown|txt|rst|adoc|html?)$/i;
|
|
13
|
+
const UPPER_TOKEN = /\b[A-Z_][A-Z0-9_]{2,}\b/g;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {{ file: string, line: number, column: number }} Location
|
|
17
|
+
* @typedef {Object} Scope
|
|
18
|
+
* @property {string} dir directory relative to root ('' = root)
|
|
19
|
+
* @property {string[]} exampleFiles example files in this directory
|
|
20
|
+
* @property {string|null} envFile local env file, if it exists
|
|
21
|
+
* @property {Map<string, Location[]>} refs
|
|
22
|
+
* @property {Map<string, {file: string, line: number, optional: boolean, value: string}>} documented
|
|
23
|
+
* @property {{name: string, refs: Location[]}[]} undocumented
|
|
24
|
+
* @property {{name: string, file: string, line: number}[]} unused
|
|
25
|
+
* @property {string[]} missingLocal
|
|
26
|
+
* @property {{name: string, file: string, line: number, firstLine: number}[]} duplicates
|
|
27
|
+
* @property {{name: string, file: string, line: number, kind: string}[]} secrets
|
|
28
|
+
* @property {'tracked'|'untracked'|'ignored'|null} envGitStatus
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Run a full audit of a project.
|
|
33
|
+
* @param {string} rootDir
|
|
34
|
+
* @param {Partial<import('./config.js').Config>} [overrides]
|
|
35
|
+
*/
|
|
36
|
+
export function audit(rootDir, overrides = {}) {
|
|
37
|
+
const root = resolve(rootDir);
|
|
38
|
+
const { config: fileConfig, source: configSource } = loadConfig(root);
|
|
39
|
+
const config = { ...fileConfig, ...stripUndefined(overrides) };
|
|
40
|
+
config.ignoreVars = [...fileConfig.ignoreVars, ...(overrides.ignoreVars ?? [])];
|
|
41
|
+
|
|
42
|
+
const skipVar = nameMatcher([...config.ignoreVars, ...(config.builtins ? BUILTIN_VARS : [])]);
|
|
43
|
+
const skipUnused = nameMatcher([...config.ignoreVars, ...config.ignoreUnused]);
|
|
44
|
+
|
|
45
|
+
const files = listFiles(root, { ignore: config.ignore });
|
|
46
|
+
|
|
47
|
+
// 1. Find example files and build scopes (one per directory holding an example)
|
|
48
|
+
let examplePaths;
|
|
49
|
+
if (config.example) {
|
|
50
|
+
examplePaths = [config.example.replace(/\\/g, '/').replace(/^\.\//, '')];
|
|
51
|
+
} else {
|
|
52
|
+
examplePaths = files.filter((f) => EXAMPLE_FILE.test(posix.basename(f)));
|
|
53
|
+
// example files are sometimes gitignored by an over-broad `.env*` rule
|
|
54
|
+
for (const name of EXAMPLE_PRIORITY) {
|
|
55
|
+
if (!examplePaths.includes(name) && existsSync(join(root, name))) examplePaths.push(name);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** @type {Map<string, Scope>} */
|
|
60
|
+
const scopes = new Map();
|
|
61
|
+
const getScope = (dir) => {
|
|
62
|
+
if (!scopes.has(dir)) {
|
|
63
|
+
scopes.set(dir, {
|
|
64
|
+
dir, exampleFiles: [], envFile: null, refs: new Map(), documented: new Map(),
|
|
65
|
+
undocumented: [], unused: [], missingLocal: [], duplicates: [], secrets: [], envGitStatus: null,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return scopes.get(dir);
|
|
69
|
+
};
|
|
70
|
+
for (const p of examplePaths) {
|
|
71
|
+
const dir = config.example ? '' : dirOf(p);
|
|
72
|
+
getScope(dir).exampleFiles.push(p);
|
|
73
|
+
}
|
|
74
|
+
// no example anywhere: everything belongs to a root scope with nothing documented
|
|
75
|
+
if (scopes.size === 0) getScope('');
|
|
76
|
+
for (const s of scopes.values()) s.exampleFiles.sort(byPriority);
|
|
77
|
+
|
|
78
|
+
const scopeDirs = [...scopes.keys()].sort((a, b) => b.length - a.length);
|
|
79
|
+
const scopeFor = (file) => scopeDirs.find((d) => d === '' || file === d || file.startsWith(d + '/'));
|
|
80
|
+
const ancestorsOf = (dir) => scopeDirs.filter((d) => d !== dir && (d === '' || dir.startsWith(d + '/')));
|
|
81
|
+
|
|
82
|
+
// 2. Parse example files
|
|
83
|
+
for (const s of scopes.values()) {
|
|
84
|
+
for (const ex of s.exampleFiles) {
|
|
85
|
+
const text = readText(join(root, ex));
|
|
86
|
+
if (text == null) continue;
|
|
87
|
+
const { entries, keys } = parseDotenv(text);
|
|
88
|
+
for (const [name, e] of keys) {
|
|
89
|
+
const prev = s.documented.get(name);
|
|
90
|
+
if (!prev || (prev.optional && !e.optional)) {
|
|
91
|
+
s.documented.set(name, { file: ex, line: e.line, optional: e.optional, value: e.value });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const d of findDuplicates(entries)) s.duplicates.push({ ...d, file: ex });
|
|
95
|
+
for (const e of entries) {
|
|
96
|
+
const kind = detectSecret(e.value);
|
|
97
|
+
if (kind) s.secrets.push({ name: e.name, file: ex, line: e.line, kind });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 3. Scan source files
|
|
103
|
+
/** @type {Map<string, Location[]>} refs outside every scope (monorepo without root example) */
|
|
104
|
+
const uncoveredRefs = new Map();
|
|
105
|
+
/** uppercase tokens mentioned anywhere under a scope dir, used to soften "unused" */
|
|
106
|
+
const mentions = new Map([...scopes.keys()].map((d) => [d, new Set()]));
|
|
107
|
+
const examples = new Set(examplePaths);
|
|
108
|
+
let scanned = 0;
|
|
109
|
+
|
|
110
|
+
for (const file of files) {
|
|
111
|
+
if (examples.has(file) || ENV_LIKE.test(file)) continue;
|
|
112
|
+
const lang = languageFor(file);
|
|
113
|
+
const prose = PROSE.test(file);
|
|
114
|
+
const scopeDir = scopeFor(file);
|
|
115
|
+
if (!lang && (prose || scopeDir === undefined)) continue;
|
|
116
|
+
const text = readText(join(root, file));
|
|
117
|
+
if (text == null) continue;
|
|
118
|
+
|
|
119
|
+
if (lang) {
|
|
120
|
+
scanned++;
|
|
121
|
+
const target = scopeDir !== undefined ? scopes.get(scopeDir).refs : uncoveredRefs;
|
|
122
|
+
for (const r of extract(text, file)) {
|
|
123
|
+
if (skipVar(r.name)) continue;
|
|
124
|
+
if (!target.has(r.name)) target.set(r.name, []);
|
|
125
|
+
target.get(r.name).push({ file, line: r.line, column: r.column });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!prose) {
|
|
129
|
+
const tokens = text.match(UPPER_TOKEN);
|
|
130
|
+
if (tokens) {
|
|
131
|
+
for (const [dir, set] of mentions) {
|
|
132
|
+
if (dir === '' || file.startsWith(dir + '/')) for (const t of tokens) set.add(t);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// 4. Compare
|
|
139
|
+
for (const s of scopes.values()) {
|
|
140
|
+
const inherited = ancestorsOf(s.dir).map((d) => scopes.get(d).documented);
|
|
141
|
+
const isDocumented = (name) => s.documented.has(name) || inherited.some((m) => m.has(name));
|
|
142
|
+
|
|
143
|
+
for (const [name, refs] of s.refs) {
|
|
144
|
+
if (!isDocumented(name)) s.undocumented.push({ name, refs });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// used anywhere in this scope's subtree (nested scopes included)
|
|
148
|
+
const usedBelow = new Set();
|
|
149
|
+
for (const t of scopes.values()) {
|
|
150
|
+
if (t.dir === s.dir || s.dir === '' || t.dir.startsWith(s.dir + '/')) for (const n of t.refs.keys()) usedBelow.add(n);
|
|
151
|
+
}
|
|
152
|
+
for (const [name, d] of s.documented) {
|
|
153
|
+
if (d.optional || usedBelow.has(name) || skipUnused(name) || (config.builtins && BUILTIN_VARS.includes(name))) continue;
|
|
154
|
+
if (mentions.get(s.dir)?.has(name)) continue; // referenced in a config/script we don't parse
|
|
155
|
+
s.unused.push({ name, file: d.file, line: d.line });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// local .env
|
|
159
|
+
const envRel = posix.join(s.dir || '.', config.env).replace(/^\.\//, '');
|
|
160
|
+
if (s.exampleFiles.length && existsSync(join(root, envRel))) {
|
|
161
|
+
s.envFile = envRel;
|
|
162
|
+
const local = parseDotenv(readFileSync(join(root, envRel), 'utf8')).keys;
|
|
163
|
+
for (const [name, d] of s.documented) {
|
|
164
|
+
if (!d.optional && (!local.has(name) || local.get(name).optional)) s.missingLocal.push(name);
|
|
165
|
+
}
|
|
166
|
+
s.envGitStatus = gitStatusOf(root, envRel);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
s.undocumented.sort(byName);
|
|
170
|
+
s.unused.sort(byName);
|
|
171
|
+
s.missingLocal.sort();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const uncovered = [...uncoveredRefs].map(([name, refs]) => ({ name, refs })).sort(byName);
|
|
175
|
+
const list = [...scopes.values()].sort((a, b) => a.dir.localeCompare(b.dir));
|
|
176
|
+
|
|
177
|
+
const counts = {
|
|
178
|
+
undocumented: sum(list, (s) => s.undocumented.length),
|
|
179
|
+
unused: sum(list, (s) => s.unused.length),
|
|
180
|
+
missingLocal: sum(list, (s) => s.missingLocal.length),
|
|
181
|
+
duplicates: sum(list, (s) => s.duplicates.length),
|
|
182
|
+
secrets: sum(list, (s) => s.secrets.length),
|
|
183
|
+
committedEnv: list.filter((s) => s.envGitStatus === 'tracked').length,
|
|
184
|
+
exposedEnv: list.filter((s) => s.envGitStatus === 'untracked').length,
|
|
185
|
+
uncovered: uncovered.length,
|
|
186
|
+
};
|
|
187
|
+
const errors = counts.undocumented + counts.secrets + counts.committedEnv;
|
|
188
|
+
const warnings = counts.unused + counts.duplicates + counts.exposedEnv;
|
|
189
|
+
const ok = errors === 0 && (!config.strict || warnings === 0);
|
|
190
|
+
|
|
191
|
+
return { root, config, configSource, filesScanned: scanned, scopes: list, uncovered, counts, ok };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function dirOf(p) {
|
|
195
|
+
const d = posix.dirname(p);
|
|
196
|
+
return d === '.' ? '' : d;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function byPriority(a, b) {
|
|
200
|
+
const pa = EXAMPLE_PRIORITY.indexOf(posix.basename(a));
|
|
201
|
+
const pb = EXAMPLE_PRIORITY.indexOf(posix.basename(b));
|
|
202
|
+
return (pa === -1 ? 99 : pa) - (pb === -1 ? 99 : pb) || a.localeCompare(b);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function byName(a, b) {
|
|
206
|
+
return a.name.localeCompare(b.name);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function sum(arr, f) {
|
|
210
|
+
return arr.reduce((n, x) => n + f(x), 0);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function stripUndefined(o) {
|
|
214
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
215
|
+
}
|