@jutaru-dev/envsonar 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jutaru
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,176 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # envsonar
2
+
3
+ [![ci](https://github.com/jutaru-dev/envsonar/actions/workflows/ci.yml/badge.svg)](https://github.com/jutaru-dev/envsonar/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@jutaru-dev/envsonar?color=2f74ff)](https://www.npmjs.com/package/@jutaru-dev/envsonar)
5
+ ![dependencies](https://img.shields.io/badge/dependencies-0-2f74ff)
6
+ ![node](https://img.shields.io/badge/node-%E2%89%A520-2f74ff)
7
+ ![license](https://img.shields.io/badge/license-MIT-2f74ff)
8
+
9
+ **Catches the env vars your code reads but `.env.example` forgot — and knows which ones your framework reads for you.**
10
+
11
+ <p align="center">
12
+ <img src="https://raw.githubusercontent.com/jutaru-dev/envsonar/main/assets/demo.svg" alt="envsonar on a monorepo: two keys missing from .env.example, one documented key nobody reads" width="100%">
13
+ </p>
14
+
15
+ Checking `.env.example` against the code isn't a new idea, and the simple version is easy: grep for `process.env.X` and `os.getenv("X")`. The trouble is that real projects mostly don't read config that way. ASP.NET Core turns `config["Jwt:Key"]` into `Jwt__Key`. pydantic-settings derives names from class fields. A zod schema parses `process.env` in one place. The postgres image reads `POSTGRES_PASSWORD` and the OpenAI SDK reads `OPENAI_API_KEY` without a single line of your code naming them.
16
+
17
+ A grep-only check misses the first group and calls the second one "unused". After a week of false alarms people switch it off. envsonar is built around that problem: it understands how each stack reads configuration, so what it reports is worth fixing.
18
+
19
+ ## What that means on a real project
20
+
21
+ The demo above is [`examples/demo`](https://github.com/jutaru-dev/envsonar/tree/main/examples/demo): a Next.js app, an ASP.NET Core API, a Python worker and a compose file sharing one `.env.example`.
22
+
23
+ | | a scan that only finds direct reads | envsonar |
24
+ | --- | --- | --- |
25
+ | missing from `.env.example` | `STRIPE_SECRET_KEY`, `REDIS_URL` | `STRIPE_SECRET_KEY`, `WORKER_QUEUE_URL` |
26
+ | documented but "unused" | 8 keys, 7 of them wrong | `LEGACY_FLAG` |
27
+ | why | can't see the zod schema, .NET config, pydantic fields, the SDKs or the postgres image | reads all of them; `REDIS_URL` has a fallback in code, so it's a note, not an error |
28
+
29
+ Before release it was also run on two private production projects, an ASP.NET Core + Next.js + compose app and a Python bot: zero false alarms between code and `.env.example`, and two real undocumented keys found.
30
+
31
+ ## Quick start
32
+
33
+ ```sh
34
+ npx @jutaru-dev/envsonar # check the current project
35
+ npx @jutaru-dev/envsonar --fix # add what's missing to .env.example (creates it if needed)
36
+ npx @jutaru-dev/envsonar --list # every variable the code reads, and where
37
+ ```
38
+
39
+ Node.js 20 or newer. No install step and no config needed. `--fix` writes each key with an empty value and a comment saying where it's read:
40
+
41
+ ```sh
42
+ # added by envsonar
43
+ # read in apps/web/src/app/api/checkout/route.ts:3
44
+ STRIPE_SECRET_KEY=
45
+ ```
46
+
47
+ ## What it checks
48
+
49
+ | | | |
50
+ | --- | --- | --- |
51
+ | ✗ | `undocumented` | read in code, not in `.env.example` |
52
+ | ✗ | `missing` | in `.env.example`, not set in `.env` and the code needs it (only when `.env` exists) |
53
+ | ! | `unused` | in `.env.example`, but nothing reads it: not your code, not a framework, SDK or image |
54
+ | ! | `defaulted` | read with a fallback (`?? "x"`, `getenv("X", 1)`, `${X:-1}`), not in `.env.example`; hidden unless `--optional` |
55
+ | ! | `empty` · `extra` · `duplicate` | in `.env`: empty value, key not documented, key defined twice |
56
+ | ✗ | `syntax` | a line in either file that isn't `KEY=VALUE` |
57
+
58
+ Errors fail the run; `--strict` makes warnings fail too. Reports contain key names, files and line numbers only. **Values are never printed**, so the output is safe in public CI logs.
59
+
60
+ ## What it understands
61
+
62
+ | Stack | Reads it picks up |
63
+ | --- | --- |
64
+ | **JS / TS** | `process.env.X`, `process.env["X"]`, `import.meta.env.X`, `Bun.env`, `Deno.env.get`, `const { X, Y = 1 } = process.env`, `const env = process.env; env.X` |
65
+ | **env schemas** | zod objects passed to `parse(process.env)`, `@t3-oss/env` `createEnv`, envalid `cleanEnv`; `.default()` / `.optional()` count as fallbacks |
66
+ | **SvelteKit · Vite** | `import { X } from "$env/static/private"`, `$env/dynamic`, `%VITE_X%` in `index.html` |
67
+ | **ASP.NET Core** | `config["Jwt:Key"]` → `Jwt__Key`, `GetValue<T>()`, `GetConnectionString("Db")` → `ConnectionStrings__Db`, `GetSection("Smtp")` binds `Smtp__*`; keys with a value in `appsettings*.json` don't need a `.env` entry; names match case-insensitively, as .NET does |
68
+ | **Python** | `os.getenv`, `os.environ[...]`, `.get` / `.setdefault`, aliases such as `env = dict(os.environ)`; **pydantic-settings** fields with `env_prefix` and `alias` |
69
+ | **Go** | `os.Getenv`, `os.LookupEnv`, struct tags `env:"X"` (caarlos0/env) and `envconfig:"X"` |
70
+ | **PHP / Laravel** | `env("X", default)`, `getenv`, `$_ENV`; framework keys Laravel reads from its own config |
71
+ | **Ruby · Rust** | `ENV["X"]`, `ENV.fetch`; `env::var`, `dotenvy::var`, `env!`, `option_env!` |
72
+ | **Prisma** | `env("DATABASE_URL")` in `schema.prisma` and `prisma.config.ts` |
73
+ | **Docker Compose** | `${X}`, `${X:-default}`, `${X:?error}`, nested `${A:-${B}}`, `$X`; `environment:` entries supply the app with values |
74
+
75
+ ### Variables nobody's code names
76
+
77
+ Some variables are read by a dependency or a container, not by you. envsonar finds the dependency in `package.json`, `pyproject.toml` / `requirements*.txt`, `composer.json`, `*.csproj` or the compose `image:`, and stops calling its variables unused. The run header says what it found: `also read by: Next.js, OpenAI SDK, postgres image`.
78
+
79
+ Covered now: Next.js, Nuxt, Auth.js, Prisma, OpenAI, Anthropic, Google AI, AWS, Google Cloud / Firebase, Sentry, libpq (`PG*`), Vercel Postgres / KV / Blob, Upstash, dotenvx, Django, Laravel, ASP.NET Core, Docker Compose, and the postgres, mysql, mariadb, mongo, redis, rabbitmq, minio, pgadmin, keycloak, clickhouse, elasticsearch, mssql, grafana, mailpit and n8n images. The whole list is one readable file, [`src/profiles.js`](https://github.com/jutaru-dev/envsonar/blob/main/src/profiles.js); adding a stack is a three-line PR.
80
+
81
+ ### What it doesn't guess
82
+
83
+ - **Dynamic reads** such as `process.env[name]` or `os.getenv(key)` can't be resolved statically. envsonar lists them with their locations (`1 dynamic read can't be checked: src/config.ts:12`) instead of silently skipping them.
84
+ - It reads source with patterns, not a full parser per language. A read hidden behind your own wrapper (`getConfig("X")`) isn't seen. Add the key to `.env.example`, or skip it with `--ignore-key`.
85
+ - Kubernetes manifests, Terraform and CI workflow files aren't scanned yet.
86
+
87
+ ## In CI
88
+
89
+ ```yaml
90
+ # .github/workflows/env.yml
91
+ name: env
92
+ on: [pull_request]
93
+ jobs:
94
+ envsonar:
95
+ runs-on: ubuntu-latest
96
+ steps:
97
+ - uses: actions/checkout@v4
98
+ - uses: actions/setup-node@v4
99
+ with:
100
+ node-version: 22
101
+ - run: npx @jutaru-dev/envsonar
102
+ ```
103
+
104
+ On GitHub Actions the findings also become annotations on the lines that caused them: the `STRIPE_SECRET_KEY` error shows up right on `route.ts:3` in the pull request diff. Elsewhere use `--format github` to force it, or `--json` for your own tooling.
105
+
106
+ `.env` is usually not in CI, so only the code ↔ `.env.example` checks run there. To check a committed env file too, pass it: `--env .env.ci`.
107
+
108
+ ## Options
109
+
110
+ | | |
111
+ | --- | --- |
112
+ | `envsonar [dir]` | project to check (default: current directory); for a monorepo, run it per app: `envsonar apps/api` |
113
+ | `--fix` | add undocumented keys to `.env.example`, creating the file if needed |
114
+ | `--optional` | also report (and `--fix`) keys that have a fallback in code |
115
+ | `--list` | print every variable the code reads, bound config sections and dynamic reads |
116
+ | `--example <path>` | default `.env.example` |
117
+ | `--env <path>` | default `.env`; checked only if it exists, unless you pass this flag |
118
+ | `--no-code` | don't scan source, only compare `.env` with `.env.example` |
119
+ | `--ignore <dir>` | skip a directory (repeatable). `node_modules`, build output, virtualenvs, worktrees and plain dirs from `.gitignore` are skipped already |
120
+ | `--ignore-key <KEY>` | skip a key; `PREFIX_*` works (repeatable). OS and CI variables (`PATH`, `CI`, `GITHUB_*`, …) are skipped already |
121
+ | `--strict` | warnings fail the run too |
122
+ | `--json` | machine-readable report |
123
+ | `--format <pretty\|github>` | `github` prints workflow annotations (automatic on GitHub Actions) |
124
+ | `--no-color` | also respects `NO_COLOR` |
125
+
126
+ The same settings can live in `.envsonarrc.json` or under `"envsonar"` in `package.json`:
127
+
128
+ ```json
129
+ {
130
+ "envsonar": {
131
+ "example": "config/.env.example",
132
+ "ignore": ["legacy"],
133
+ "ignoreKeys": ["INTERNAL_*"],
134
+ "optional": true
135
+ }
136
+ }
137
+ ```
138
+
139
+ **Exit codes:** `0` clean · `1` errors found · `2` bad usage, unreadable file, or no `.env.example` (run `--fix` to create one).
140
+
141
+ ## From code
142
+
143
+ ```js
144
+ import { scanProject, parseEnv, check } from "@jutaru-dev/envsonar";
145
+ import { readFileSync } from "node:fs";
146
+
147
+ const scan = scanProject(".");
148
+ const findings = check({
149
+ example: parseEnv(readFileSync(".env.example", "utf8")),
150
+ exampleFile: ".env.example",
151
+ scan,
152
+ });
153
+ ```
154
+
155
+ `findings` is an array of `{ severity, code, key, file, line, message }`. `scan.usages` maps every key to the places it's read.
156
+
157
+ ## Alternatives
158
+
159
+ There are plenty of tools around `.env` files; pick the one that matches the job.
160
+
161
+ - [dotenv-linter](https://github.com/dotenv-linter/dotenv-linter): style and syntax of `.env` files themselves.
162
+ - [envalid](https://github.com/af/envalid), [@t3-oss/env](https://github.com/t3-oss/t3-env): validate variables at runtime. envsonar reads their schemas, so the two work together.
163
+ - [dotenvx](https://github.com/dotenvx/dotenvx): encrypted `.env` files.
164
+ - [envsleuth](https://pypi.org/project/envsleuth), [dotenv-scan](https://dev.to/flyingsquirrel0419/i-got-tired-of-deploying-broken-configs-so-i-built-dotenv-scan-47lb), [env-check](https://github.com/SemTiOne/env-check): also compare code with `.env.example`. envsleuth has SARIF output.
165
+
166
+ envsonar's focus is a mixed-stack repository and few false alarms: framework-specific config reads, implicit consumers, and defaults told apart from required keys.
167
+
168
+ ## Development
169
+
170
+ ```sh
171
+ node --test # the whole suite, no install needed
172
+ ```
173
+
174
+ ## License
175
+
176
+ MIT © Jutaru
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ import { run } from "../src/cli.js";
4
+
5
+ process.exitCode = run(process.argv.slice(2), {
6
+ out: (s) => process.stdout.write(s + "\n"),
7
+ err: (s) => process.stderr.write(s + "\n"),
8
+ cwd: process.cwd(),
9
+ color: Boolean(process.stdout.isTTY) && !("NO_COLOR" in process.env),
10
+ githubActions: process.env.GITHUB_ACTIONS === "true",
11
+ });
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
- {
2
- "name": "@jutaru-dev/envsonar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@jutaru-dev/envsonar",
3
+ "version": "0.1.0",
4
+ "description": "Catches env vars your code reads but .env.example forgot — and knows which ones .NET config, pydantic, Prisma, compose and SDKs read for you. Zero dependencies, never prints a value.",
5
+ "type": "module",
6
+ "bin": {
7
+ "envsonar": "bin/envsonar.js"
8
+ },
9
+ "exports": {
10
+ ".": "./src/index.js"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "src"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "typecheck": "tsc -p jsconfig.json"
22
+ },
23
+ "keywords": [
24
+ "dotenv",
25
+ "env",
26
+ "env-example",
27
+ "environment-variables",
28
+ "lint",
29
+ "ci",
30
+ "github-actions",
31
+ "monorepo",
32
+ "aspnetcore",
33
+ "pydantic-settings",
34
+ "prisma",
35
+ "docker-compose",
36
+ "laravel"
37
+ ],
38
+ "author": "Jutaru (https://github.com/jutaru-dev)",
39
+ "license": "MIT",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/jutaru-dev/envsonar.git"
43
+ },
44
+ "bugs": "https://github.com/jutaru-dev/envsonar/issues",
45
+ "homepage": "https://github.com/jutaru-dev/envsonar#readme"
46
+ }
package/src/check.js ADDED
@@ -0,0 +1,146 @@
1
+ // @ts-check
2
+ import { keyMatcher } from "./scan.js";
3
+
4
+ /**
5
+ * @typedef {import("./parse.js").ParsedEnv} ParsedEnv
6
+ * @typedef {import("./scan.js").Usage} Usage
7
+ * @typedef {import("./scan.js").ScanResult} ScanResult
8
+ * @typedef {"error" | "warning"} Severity
9
+ * @typedef {"undocumented" | "defaulted" | "unused" | "missing" | "empty" | "extra" | "duplicate" | "syntax"} Code
10
+ * @typedef {{
11
+ * severity: Severity,
12
+ * code: Code,
13
+ * key?: string,
14
+ * file: string,
15
+ * line?: number,
16
+ * message: string,
17
+ * usages?: Usage[],
18
+ * }} Finding
19
+ * @typedef {{
20
+ * example: ParsedEnv,
21
+ * exampleFile: string,
22
+ * env?: ParsedEnv | null,
23
+ * envFile?: string,
24
+ * scan?: ScanResult | null,
25
+ * strict?: boolean,
26
+ * }} CheckInput
27
+ */
28
+
29
+ /**
30
+ * Cross-checks three sources of truth: the code, .env.example and (when present) .env.
31
+ * Findings carry key names, files and line numbers only — values are never copied,
32
+ * so a report can't leak a secret.
33
+ *
34
+ * Reads with a fallback in code come back as `defaulted` (a warning) instead of `undocumented`;
35
+ * callers decide whether to show them.
36
+ *
37
+ * @param {CheckInput} input
38
+ * @returns {Finding[]}
39
+ */
40
+ export function check({ example, exampleFile, env = null, envFile = ".env", scan = null, strict = false }) {
41
+ /** @type {Severity} */
42
+ const warn = strict ? "error" : "warning";
43
+ /** @type {Finding[]} */
44
+ const findings = [];
45
+
46
+ /** @type {[ParsedEnv, string][]} */
47
+ const files = [[example, exampleFile]];
48
+ if (env) files.push([env, envFile]);
49
+ for (const [parsed, file] of files) {
50
+ for (const e of parsed.errors) findings.push({ severity: "error", code: "syntax", file, line: e.line, message: e.message });
51
+ for (const d of parsed.duplicates) {
52
+ findings.push({
53
+ severity: warn,
54
+ code: "duplicate",
55
+ key: d.key,
56
+ file,
57
+ line: d.lines[d.lines.length - 1],
58
+ message: `defined ${d.lines.length} times (lines ${d.lines.join(", ")})`,
59
+ });
60
+ }
61
+ }
62
+
63
+ if (scan) {
64
+ const exampleLower = new Set([...example.entries.keys()].map((k) => k.toLowerCase()));
65
+ for (const [key, uses] of [...scan.usages].sort(([a], [b]) => a.localeCompare(b))) {
66
+ const ci = uses.every((u) => u.ci);
67
+ if (example.entries.has(key) || (ci && exampleLower.has(key.toLowerCase()))) continue;
68
+ const provided = scan.provided.get(key.toLowerCase());
69
+ if (provided && (ci || provided.key === key)) continue;
70
+ const defaulted = uses.every((u) => u.optional);
71
+ findings.push({
72
+ severity: defaulted ? warn : "error",
73
+ code: defaulted ? "defaulted" : "undocumented",
74
+ key,
75
+ file: uses[0].file,
76
+ line: uses[0].line,
77
+ message: defaulted ? `has a default in code, missing from ${exampleFile}` : `used in code, missing from ${exampleFile}`,
78
+ usages: uses,
79
+ });
80
+ }
81
+
82
+ const consumed = consumedBy(scan);
83
+ for (const [key, entry] of example.entries) {
84
+ if (!consumed(key)) {
85
+ findings.push({ severity: warn, code: "unused", key, file: exampleFile, line: entry.line, message: "documented but never read in code" });
86
+ }
87
+ }
88
+ }
89
+
90
+ if (env) {
91
+ // a key the code reads with a fallback (or not at all) can be left out of .env: that's a warning, not an error
92
+ const needed = (/** @type {string} */ key) => !scan || Boolean(scan.usages.get(key)?.some((u) => !u.optional));
93
+ for (const [key, entry] of example.entries) {
94
+ const actual = env.entries.get(key);
95
+ if (!actual) {
96
+ const severity = needed(key) ? "error" : warn;
97
+ findings.push({ severity, code: "missing", key, file: exampleFile, line: entry.line, message: `not set in ${envFile}` });
98
+ } else if (actual.value === "") {
99
+ findings.push({ severity: warn, code: "empty", key, file: envFile, line: actual.line, message: "is empty" });
100
+ }
101
+ }
102
+ for (const [key, entry] of env.entries) {
103
+ if (!example.entries.has(key)) {
104
+ findings.push({ severity: warn, code: "extra", key, file: envFile, line: entry.line, message: `not documented in ${exampleFile}` });
105
+ }
106
+ }
107
+ }
108
+
109
+ // errors first; sort is stable, so the order inside each group is kept
110
+ return findings.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
111
+ }
112
+
113
+ /**
114
+ * Does anything read this key: the code, a bound .NET config section, appsettings.json, or an SDK / framework / image?
115
+ *
116
+ * @param {ScanResult} scan
117
+ * @returns {(key: string) => boolean}
118
+ */
119
+ function consumedBy(scan) {
120
+ const ciKeys = new Set([...scan.usages].filter(([, uses]) => uses.some((u) => u.ci)).map(([k]) => k.toLowerCase()));
121
+ const sections = [...scan.sections.keys()].map((p) => p.toLowerCase());
122
+ const implicit = keyMatcher(scan.implicit.flatMap((i) => i.keys));
123
+ return (key) => {
124
+ const lower = key.toLowerCase();
125
+ if (scan.usages.has(key) || ciKeys.has(lower) || implicit(key)) return true;
126
+ if (sections.some((p) => lower.startsWith(p))) return true;
127
+ return /(^|\/)appsettings[^/]*\.json$/i.test(scan.provided.get(lower)?.source ?? "");
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Text to append to .env.example so every given key gets an empty entry,
133
+ * each with a comment pointing at where the code reads it.
134
+ *
135
+ * @param {Finding[]} findings `undocumented` (and, if wanted, `defaulted`) findings
136
+ * @param {boolean} fileIsEmpty
137
+ */
138
+ export function fixText(findings, fileIsEmpty) {
139
+ const add = findings.filter((f) => (f.code === "undocumented" || f.code === "defaulted") && f.key);
140
+ if (add.length === 0) return "";
141
+ const lines = fileIsEmpty ? [] : [""];
142
+ lines.push("# added by envsonar");
143
+ // the hint goes on its own line: Docker's env_file and some loaders treat inline `#` as part of the value
144
+ for (const f of add) lines.push(`# read in ${f.file}:${f.line}${f.code === "defaulted" ? " (has a default)" : ""}`, `${f.key}=`);
145
+ return lines.join("\n") + "\n";
146
+ }