@webbuilder135/envsentinel 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 WebBuilder135
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 ADDED
@@ -0,0 +1,9 @@
1
+ # envsentinel
2
+
3
+ Audit `.env` against a required env file (typically `.env.example`). Optionally scans your repo for env usage (best-effort) and reports missing/empty/extra keys. CI-friendly exit codes.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i envsentinel
9
+
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../src/cli.js";
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@webbuilder135/envsentinel",
3
+ "version": "0.1.0",
4
+ "description": "Audit .env against a required env file (.env.example). CI-friendly.",
5
+ "type": "module",
6
+ "bin": "./bin/envsentinel.js",
7
+ "exports": {
8
+ ".": "./src/index.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "lint": "node -c bin/envsentinel.js && node -c src/cli.js && node -c src/index.js"
22
+ },
23
+ "keywords": ["dotenv", "env", "config", "ci", "audit", "lint"],
24
+ "license": "MIT",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ }
28
+ }
package/src/cli.js ADDED
@@ -0,0 +1,104 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { auditProject, proReportHtml } from "./index.js";
4
+
5
+ function parseArgs(argv) {
6
+ const args = { root: process.cwd(), json: false, verbose: false };
7
+ for (let i = 2; i < argv.length; i++) {
8
+ const a = argv[i];
9
+ const v = argv[i + 1];
10
+
11
+ if (a === "--env") {
12
+ args.env = v; i++;
13
+ } else if (a === "--required") {
14
+ args.required = v; i++;
15
+ } else if (a === "--root") {
16
+ args.root = v; i++;
17
+ } else if (a === "--json") {
18
+ args.json = true;
19
+ } else if (a === "--html") {
20
+ args.html = v; i++;
21
+ } else if (a === "--verbose" || a === "-v") {
22
+ args.verbose = true;
23
+ } else if (a === "-h" || a === "--help") {
24
+ args.help = true;
25
+ } else {
26
+ args.unknown ??= [];
27
+ args.unknown.push(a);
28
+ }
29
+ }
30
+ return args;
31
+ }
32
+
33
+ function usage() {
34
+ console.log(`
35
+ envsentinel --env .env --required .env.example [--root .] [--json] [--html report.html] [--verbose]
36
+
37
+ Options:
38
+ --env <path> Path to .env file
39
+ --required <path> Path to required env file (e.g. .env.example)
40
+ --root <dir> Repo root to scan for env usage (default: cwd)
41
+ --json Print full JSON result
42
+ --verbose, -v Print additional hints (UnusedRequired)
43
+ --html <path> (Pro) Write HTML report
44
+
45
+ Exit codes:
46
+ 0 = OK
47
+ 1 = missing required keys OR empty required values
48
+ 2 = invalid args / missing files / runtime error
49
+ `.trim());
50
+ }
51
+
52
+ function ensureFile(p, label) {
53
+ if (!p) throw new Error(`Missing ${label}`);
54
+ if (!fs.existsSync(p)) throw new Error(`File not found: ${p}`);
55
+ return path.resolve(p);
56
+ }
57
+
58
+ function printHuman(r, { verbose }) {
59
+ const line = (k, arr) => console.log(`${k}: ${arr.length ? arr.join(", ") : "-"}`);
60
+ line("Missing", r.missing);
61
+ line("Empty", r.empty);
62
+ line("Extra", r.extra);
63
+ if (verbose) line("UnusedRequired", r.unusedRequired);
64
+ }
65
+
66
+ async function main() {
67
+ const args = parseArgs(process.argv);
68
+
69
+ if (args.help) {
70
+ usage();
71
+ return;
72
+ }
73
+
74
+ if (args.unknown?.length) {
75
+ console.error(`Unknown args: ${args.unknown.join(", ")}`);
76
+ usage();
77
+ process.exit(2);
78
+ }
79
+
80
+ try {
81
+ const envPath = ensureFile(args.env, "--env");
82
+ const requiredPath = ensureFile(args.required, "--required");
83
+ const rootDir = path.resolve(args.root);
84
+
85
+ const result = await auditProject({ envPath, requiredPath, rootDir });
86
+
87
+ if (args.json) console.log(JSON.stringify(result, null, 2));
88
+ else printHuman(result, { verbose: args.verbose });
89
+
90
+ if (args.html) {
91
+ const html = await proReportHtml(result);
92
+ fs.writeFileSync(args.html, html, "utf8");
93
+ console.log(`Wrote ${args.html}`);
94
+ }
95
+
96
+ const bad = result.missing.length > 0 || result.empty.length > 0;
97
+ process.exit(bad ? 1 : 0);
98
+ } catch (err) {
99
+ console.error(String(err?.message ?? err));
100
+ process.exit(2);
101
+ }
102
+ }
103
+
104
+ main();
@@ -0,0 +1,27 @@
1
+ export function auditEnv({ requiredKeys, envMap, repoUsedKeys = [] }) {
2
+ const required = new Set(requiredKeys);
3
+ const present = new Set(envMap.keys());
4
+ const used = new Set(repoUsedKeys);
5
+
6
+ const missing = [...required].filter((k) => !present.has(k)).sort();
7
+
8
+ const empty = [...required]
9
+ .filter((k) => present.has(k))
10
+ .filter((k) => (envMap.get(k) ?? "").trim() === "")
11
+ .sort();
12
+
13
+ const extra = [...present].filter((k) => !required.has(k)).sort();
14
+
15
+ // "required but not used anywhere in repo" (useful hint)
16
+ const unusedRequired = [...required].filter((k) => present.has(k) && !used.has(k)).sort();
17
+
18
+ return {
19
+ required: [...required].sort(),
20
+ present: [...present].sort(),
21
+ used: [...used].sort(),
22
+ missing,
23
+ empty,
24
+ extra,
25
+ unusedRequired
26
+ };
27
+ }
@@ -0,0 +1,56 @@
1
+ import fs from "node:fs";
2
+
3
+ export function parseEnvContent(content) {
4
+ const map = new Map();
5
+ const lines = content.split(/\r?\n/);
6
+
7
+ for (let line of lines) {
8
+ line = line.trim();
9
+ if (!line || line.startsWith("#")) continue;
10
+
11
+ // support: export KEY=VALUE
12
+ if (line.startsWith("export ")) line = line.slice(7).trim();
13
+
14
+ const eq = line.indexOf("=");
15
+ if (eq === -1) continue;
16
+
17
+ const key = line.slice(0, eq).trim();
18
+ let value = line.slice(eq + 1).trim();
19
+
20
+ // strip inline comment only if unquoted
21
+ const isQuoted =
22
+ (value.startsWith('"') && value.endsWith('"')) ||
23
+ (value.startsWith("'") && value.endsWith("'"));
24
+
25
+ if (!isQuoted) {
26
+ // remove " #comment" style
27
+ const idx = value.indexOf(" #");
28
+ if (idx !== -1) value = value.slice(0, idx).trim();
29
+ if (value.startsWith("#")) value = "";
30
+ }
31
+
32
+ // unquote
33
+ if (
34
+ (value.startsWith('"') && value.endsWith('"')) ||
35
+ (value.startsWith("'") && value.endsWith("'"))
36
+ ) {
37
+ value = value.slice(1, -1);
38
+ }
39
+
40
+ // minimal escapes (double quotes common)
41
+ value = value
42
+ .replace(/\\n/g, "\n")
43
+ .replace(/\\r/g, "\r")
44
+ .replace(/\\t/g, "\t")
45
+ .replace(/\\"/g, '"');
46
+
47
+ if (key) map.set(key, value);
48
+ }
49
+
50
+ return map;
51
+ }
52
+
53
+ export function parseEnvFile(filePath) {
54
+ const content = fs.readFileSync(filePath, "utf8");
55
+ return parseEnvContent(content);
56
+ }
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ const DEFAULT_IGNORE_DIRS = new Set([
5
+ "node_modules",
6
+ ".git",
7
+ "dist",
8
+ "build",
9
+ ".next",
10
+ ".cache",
11
+ "coverage"
12
+ ]);
13
+
14
+ // Intentionally exclude .md and .env* to reduce false positives from docs/examples.
15
+ const DEFAULT_EXT_RE = /\.(js|cjs|mjs|ts|tsx|jsx|json|yml|yaml|sh|ps1|toml|ini)$/i;
16
+
17
+ export function scanRepoForEnvUsage(rootDir, { ignoreDirs = DEFAULT_IGNORE_DIRS } = {}) {
18
+ const used = new Set();
19
+
20
+ function walk(dir) {
21
+ let entries;
22
+ try {
23
+ entries = fs.readdirSync(dir, { withFileTypes: true });
24
+ } catch {
25
+ return;
26
+ }
27
+
28
+ for (const entry of entries) {
29
+ const full = path.join(dir, entry.name);
30
+
31
+ if (entry.isDirectory()) {
32
+ if (ignoreDirs.has(entry.name)) continue;
33
+ walk(full);
34
+ continue;
35
+ }
36
+
37
+ // skip dotenv files explicitly
38
+ if (entry.name === ".env" || entry.name.startsWith(".env.")) continue;
39
+
40
+ if (!DEFAULT_EXT_RE.test(entry.name)) continue;
41
+
42
+ let text;
43
+ try {
44
+ text = fs.readFileSync(full, "utf8");
45
+ } catch {
46
+ continue;
47
+ }
48
+
49
+ for (const m of text.matchAll(/\bprocess\.env\.([A-Z0-9_]+)\b/g)) {
50
+ used.add(m[1]);
51
+ }
52
+
53
+ for (const m of text.matchAll(/\bprocess\.env\[(["'])([A-Z0-9_]+)\1\]/g)) {
54
+ used.add(m[2]);
55
+ }
56
+
57
+ for (const m of text.matchAll(/\$\{([A-Z][A-Z0-9_]{2,})\}/g)) {
58
+ used.add(m[1]);
59
+ }
60
+ }
61
+ }
62
+
63
+ walk(rootDir);
64
+ return [...used].sort();
65
+ }
package/src/index.js ADDED
@@ -0,0 +1,28 @@
1
+ import { parseEnvFile } from "./env/parseEnvFile.js";
2
+ import { scanRepoForEnvUsage } from "./env/scanRepo.js";
3
+ import { auditEnv } from "./env/audit.js";
4
+ import { loadPro } from "./pro-loader.js";
5
+
6
+ export { parseEnvFile, scanRepoForEnvUsage, auditEnv };
7
+
8
+ export async function auditProject({ envPath, requiredPath, rootDir = process.cwd() }) {
9
+ const required = parseEnvFile(requiredPath);
10
+ const env = parseEnvFile(envPath);
11
+ const usedKeys = scanRepoForEnvUsage(rootDir);
12
+
13
+ return auditEnv({
14
+ requiredKeys: [...required.keys()],
15
+ envMap: env,
16
+ repoUsedKeys: usedKeys
17
+ });
18
+ }
19
+
20
+ export async function proReportHtml(auditResult) {
21
+ const pro = await loadPro();
22
+ if (!pro?.proReportHtml) {
23
+ throw new Error(
24
+ "Pro not available: install pro.js next to package root (node_modules/envsentinel/pro.js)."
25
+ );
26
+ }
27
+ return pro.proReportHtml(auditResult);
28
+ }
@@ -0,0 +1,14 @@
1
+ export async function loadPro() {
2
+ try {
3
+ const mod = await import("../pro.js");
4
+ return mod?.default ?? mod;
5
+ } catch (err) {
6
+ if (
7
+ err?.code === "ERR_MODULE_NOT_FOUND" ||
8
+ err?.code === "MODULE_NOT_FOUND"
9
+ ) {
10
+ return null;
11
+ }
12
+ throw err;
13
+ }
14
+ }