@subramanyaks/env-drift 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/dist/cli.js +720 -0
- package/dist/index.cjs +589 -0
- package/dist/index.d.cts +126 -0
- package/dist/index.d.ts +126 -0
- package/dist/index.js +537 -0
- package/package.json +67 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { realpathSync } from "fs";
|
|
5
|
+
import { resolve as resolve2 } from "path";
|
|
6
|
+
import { fileURLToPath } from "url";
|
|
7
|
+
import { parseArgs } from "util";
|
|
8
|
+
import pc2 from "picocolors";
|
|
9
|
+
|
|
10
|
+
// package.json
|
|
11
|
+
var package_default = {
|
|
12
|
+
name: "@subramanyaks/env-drift",
|
|
13
|
+
version: "1.0.1",
|
|
14
|
+
description: "Zero-config CLI and library to detect environment variable drift, missing keys, dead vars, and accidental public secret exposure.",
|
|
15
|
+
type: "module",
|
|
16
|
+
publishConfig: {
|
|
17
|
+
access: "public"
|
|
18
|
+
},
|
|
19
|
+
main: "./dist/index.cjs",
|
|
20
|
+
module: "./dist/index.js",
|
|
21
|
+
types: "./dist/index.d.ts",
|
|
22
|
+
bin: {
|
|
23
|
+
"env-drift": "./dist/cli.js"
|
|
24
|
+
},
|
|
25
|
+
exports: {
|
|
26
|
+
".": {
|
|
27
|
+
types: "./dist/index.d.ts",
|
|
28
|
+
import: "./dist/index.js",
|
|
29
|
+
require: "./dist/index.cjs"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
files: [
|
|
33
|
+
"dist",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
],
|
|
37
|
+
engines: {
|
|
38
|
+
node: ">=18.17.0"
|
|
39
|
+
},
|
|
40
|
+
scripts: {
|
|
41
|
+
dev: "tsup --watch",
|
|
42
|
+
build: "tsup",
|
|
43
|
+
typecheck: "tsc --noEmit",
|
|
44
|
+
test: "vitest run",
|
|
45
|
+
"test:watch": "vitest",
|
|
46
|
+
prepublishOnly: "npm run typecheck && npm test && npm run build"
|
|
47
|
+
},
|
|
48
|
+
repository: {
|
|
49
|
+
type: "git",
|
|
50
|
+
url: "https://github.com/SubramanyaKS/env-drift.git"
|
|
51
|
+
},
|
|
52
|
+
bugs: {
|
|
53
|
+
url: "https://github.com/SubramanyaKS/env-drift/issues"
|
|
54
|
+
},
|
|
55
|
+
keywords: [
|
|
56
|
+
"env",
|
|
57
|
+
"dotenv",
|
|
58
|
+
"env-drift",
|
|
59
|
+
"environment",
|
|
60
|
+
"cli",
|
|
61
|
+
"security",
|
|
62
|
+
"audit",
|
|
63
|
+
"typescript",
|
|
64
|
+
"ci",
|
|
65
|
+
"nextjs",
|
|
66
|
+
"vite"
|
|
67
|
+
],
|
|
68
|
+
author: "SubramanyaKS",
|
|
69
|
+
license: "MIT",
|
|
70
|
+
dependencies: {
|
|
71
|
+
picocolors: "^1.1.1"
|
|
72
|
+
},
|
|
73
|
+
devDependencies: {
|
|
74
|
+
"@types/node": "^22.20.7",
|
|
75
|
+
tsup: "^8.5.1",
|
|
76
|
+
typescript: "^5.9.3",
|
|
77
|
+
vitest: "^4.0.18"
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// src/analyzer.ts
|
|
82
|
+
import { resolve } from "path";
|
|
83
|
+
|
|
84
|
+
// src/envParser.ts
|
|
85
|
+
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
86
|
+
var ENV_LINE_REGEX = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
|
87
|
+
function parseValue(raw) {
|
|
88
|
+
const trimmed = raw.trim();
|
|
89
|
+
if (!trimmed) return "";
|
|
90
|
+
const quote = trimmed[0];
|
|
91
|
+
if (quote === '"') {
|
|
92
|
+
let result = "";
|
|
93
|
+
for (let i = 1; i < trimmed.length; i++) {
|
|
94
|
+
const ch = trimmed[i];
|
|
95
|
+
if (ch === "\\" && i + 1 < trimmed.length) {
|
|
96
|
+
const next = trimmed[i + 1];
|
|
97
|
+
if (next === "n") result += "\n";
|
|
98
|
+
else if (next === "r") result += "\r";
|
|
99
|
+
else if (next === "t") result += " ";
|
|
100
|
+
else result += next;
|
|
101
|
+
i++;
|
|
102
|
+
} else if (ch === '"') {
|
|
103
|
+
return result;
|
|
104
|
+
} else {
|
|
105
|
+
result += ch;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
if (quote === "'") {
|
|
111
|
+
const closingIdx = trimmed.indexOf("'", 1);
|
|
112
|
+
if (closingIdx !== -1) {
|
|
113
|
+
return trimmed.slice(1, closingIdx);
|
|
114
|
+
}
|
|
115
|
+
return trimmed.slice(1);
|
|
116
|
+
}
|
|
117
|
+
const commentIdx = trimmed.indexOf(" #");
|
|
118
|
+
if (commentIdx !== -1) {
|
|
119
|
+
return trimmed.slice(0, commentIdx).trim();
|
|
120
|
+
}
|
|
121
|
+
return trimmed;
|
|
122
|
+
}
|
|
123
|
+
function parseEnvContent(content) {
|
|
124
|
+
const keys = [];
|
|
125
|
+
const seen = /* @__PURE__ */ new Set();
|
|
126
|
+
const duplicateSet = /* @__PURE__ */ new Set();
|
|
127
|
+
const values = {};
|
|
128
|
+
const lines = content.split(/\r?\n/);
|
|
129
|
+
for (const rawLine of lines) {
|
|
130
|
+
const line = rawLine.trim();
|
|
131
|
+
if (!line || line.startsWith("#")) continue;
|
|
132
|
+
const match = ENV_LINE_REGEX.exec(line);
|
|
133
|
+
if (!match) continue;
|
|
134
|
+
const key = match[1];
|
|
135
|
+
const rawValue = match[2] ?? "";
|
|
136
|
+
if (!key) continue;
|
|
137
|
+
if (seen.has(key)) {
|
|
138
|
+
duplicateSet.add(key);
|
|
139
|
+
} else {
|
|
140
|
+
seen.add(key);
|
|
141
|
+
keys.push(key);
|
|
142
|
+
}
|
|
143
|
+
values[key] = parseValue(rawValue);
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
keys,
|
|
147
|
+
values,
|
|
148
|
+
duplicates: Array.from(duplicateSet)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function parseEnvFile(filePath) {
|
|
152
|
+
if (!existsSync(filePath)) {
|
|
153
|
+
return {
|
|
154
|
+
filePath,
|
|
155
|
+
exists: false,
|
|
156
|
+
keys: [],
|
|
157
|
+
values: {},
|
|
158
|
+
duplicates: []
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const content = readFileSync(filePath, "utf-8");
|
|
162
|
+
const { keys, values, duplicates } = parseEnvContent(content);
|
|
163
|
+
return {
|
|
164
|
+
filePath,
|
|
165
|
+
exists: true,
|
|
166
|
+
keys,
|
|
167
|
+
values,
|
|
168
|
+
duplicates
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function syncEnvExample(examplePath, missingKeys) {
|
|
172
|
+
const uniqueKeys = Array.from(new Set(missingKeys)).sort();
|
|
173
|
+
if (uniqueKeys.length === 0) {
|
|
174
|
+
return { added: [], created: false };
|
|
175
|
+
}
|
|
176
|
+
const created = !existsSync(examplePath);
|
|
177
|
+
const existingContent = created ? "" : readFileSync(examplePath, "utf-8");
|
|
178
|
+
const existingKeys = new Set(parseEnvContent(existingContent).keys);
|
|
179
|
+
const toAdd = uniqueKeys.filter((k) => !existingKeys.has(k));
|
|
180
|
+
if (toAdd.length === 0) {
|
|
181
|
+
return { added: [], created: false };
|
|
182
|
+
}
|
|
183
|
+
const linesBlock = toAdd.map((k) => `${k}=`).join("\n") + "\n";
|
|
184
|
+
let nextContent;
|
|
185
|
+
if (created || existingContent.trim() === "") {
|
|
186
|
+
nextContent = linesBlock;
|
|
187
|
+
} else {
|
|
188
|
+
const separator = existingContent.endsWith("\n") ? "" : "\n";
|
|
189
|
+
nextContent = `${existingContent}${separator}${linesBlock}`;
|
|
190
|
+
}
|
|
191
|
+
writeFileSync(examplePath, nextContent, "utf-8");
|
|
192
|
+
return { added: toAdd, created };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/scanner.ts
|
|
196
|
+
import { readdirSync, readFileSync as readFileSync2, statSync } from "fs";
|
|
197
|
+
import { extname, join, relative } from "path";
|
|
198
|
+
var DEFAULT_IGNORE_DIRS = /* @__PURE__ */ new Set([
|
|
199
|
+
"node_modules",
|
|
200
|
+
".git",
|
|
201
|
+
"dist",
|
|
202
|
+
"build",
|
|
203
|
+
".next",
|
|
204
|
+
".nuxt",
|
|
205
|
+
".svelte-kit",
|
|
206
|
+
".vercel",
|
|
207
|
+
".turbo",
|
|
208
|
+
"coverage",
|
|
209
|
+
"out",
|
|
210
|
+
".cache"
|
|
211
|
+
]);
|
|
212
|
+
var DEFAULT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
213
|
+
".js",
|
|
214
|
+
".jsx",
|
|
215
|
+
".ts",
|
|
216
|
+
".tsx",
|
|
217
|
+
".mjs",
|
|
218
|
+
".cjs",
|
|
219
|
+
".mts",
|
|
220
|
+
".cts",
|
|
221
|
+
".vue",
|
|
222
|
+
".svelte",
|
|
223
|
+
".astro"
|
|
224
|
+
]);
|
|
225
|
+
function stripCommentsPreservingLines(source) {
|
|
226
|
+
const tokenRegex = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g;
|
|
227
|
+
return source.replace(tokenRegex, (match, stringLiteral) => {
|
|
228
|
+
if (stringLiteral) return match;
|
|
229
|
+
return match.replace(/[^\r\n]/g, " ");
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
function getLineNumber(source, index) {
|
|
233
|
+
let line = 1;
|
|
234
|
+
for (let i = 0; i < index; i++) {
|
|
235
|
+
if (source.charCodeAt(i) === 10) line++;
|
|
236
|
+
}
|
|
237
|
+
return line;
|
|
238
|
+
}
|
|
239
|
+
function extractEnvReferences(content, filePath) {
|
|
240
|
+
const cleaned = stripCommentsPreservingLines(content);
|
|
241
|
+
const refs = [];
|
|
242
|
+
const normalizedFile = filePath.replace(/\\/g, "/");
|
|
243
|
+
const dotRegex = /\b(process\.env|import\.meta\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
|
|
244
|
+
for (const match of cleaned.matchAll(dotRegex)) {
|
|
245
|
+
const source = match[1];
|
|
246
|
+
const name = match[2];
|
|
247
|
+
if (!name || match.index === void 0) continue;
|
|
248
|
+
refs.push({
|
|
249
|
+
name,
|
|
250
|
+
file: normalizedFile,
|
|
251
|
+
line: getLineNumber(cleaned, match.index),
|
|
252
|
+
source
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
const bracketRegex = /\b(process\.env|import\.meta\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
|
|
256
|
+
for (const match of cleaned.matchAll(bracketRegex)) {
|
|
257
|
+
const source = match[1];
|
|
258
|
+
const name = match[2];
|
|
259
|
+
if (!name || match.index === void 0) continue;
|
|
260
|
+
refs.push({
|
|
261
|
+
name,
|
|
262
|
+
file: normalizedFile,
|
|
263
|
+
line: getLineNumber(cleaned, match.index),
|
|
264
|
+
source
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
|
|
268
|
+
for (const match of cleaned.matchAll(destructureRegex)) {
|
|
269
|
+
const body = match[1];
|
|
270
|
+
const source = match[2];
|
|
271
|
+
if (!body || match.index === void 0) continue;
|
|
272
|
+
const bodyStart = match.index + 1;
|
|
273
|
+
let offset = 0;
|
|
274
|
+
for (const part of body.split(",")) {
|
|
275
|
+
const partIdx = body.indexOf(part, offset);
|
|
276
|
+
offset = partIdx + part.length + 1;
|
|
277
|
+
const trimmed = part.trim();
|
|
278
|
+
if (!trimmed || trimmed.startsWith("...")) continue;
|
|
279
|
+
const keyMatch = /^([A-Za-z_][A-Za-z0-9_]*)/.exec(trimmed);
|
|
280
|
+
const name = keyMatch?.[1];
|
|
281
|
+
if (!name) continue;
|
|
282
|
+
const leadingWs = part.indexOf(name);
|
|
283
|
+
const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
|
|
284
|
+
refs.push({
|
|
285
|
+
name,
|
|
286
|
+
file: normalizedFile,
|
|
287
|
+
line: getLineNumber(cleaned, absoluteIdx),
|
|
288
|
+
source
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
refs.sort((a, b) => a.line - b.line);
|
|
293
|
+
return refs;
|
|
294
|
+
}
|
|
295
|
+
function scanFiles(rootDir, options = {}) {
|
|
296
|
+
const ignoreDirs = options.ignoreDirs ? new Set(options.ignoreDirs) : DEFAULT_IGNORE_DIRS;
|
|
297
|
+
const extensions = options.extensions ? new Set(options.extensions) : DEFAULT_EXTENSIONS;
|
|
298
|
+
let scannedFiles = 0;
|
|
299
|
+
const references = [];
|
|
300
|
+
function walk(currentDir) {
|
|
301
|
+
const entries = readdirSync(currentDir, { withFileTypes: true });
|
|
302
|
+
for (const entry of entries) {
|
|
303
|
+
const fullPath = join(currentDir, entry.name);
|
|
304
|
+
if (entry.isDirectory()) {
|
|
305
|
+
if (ignoreDirs.has(entry.name)) continue;
|
|
306
|
+
walk(fullPath);
|
|
307
|
+
} else if (entry.isFile()) {
|
|
308
|
+
const ext = extname(entry.name).toLowerCase();
|
|
309
|
+
if (!extensions.has(ext)) continue;
|
|
310
|
+
const size = statSync(fullPath).size;
|
|
311
|
+
if (size > 2 * 1024 * 1024) continue;
|
|
312
|
+
scannedFiles++;
|
|
313
|
+
const content = readFileSync2(fullPath, "utf-8");
|
|
314
|
+
const relPath = relative(rootDir, fullPath);
|
|
315
|
+
const fileRefs = extractEnvReferences(content, relPath);
|
|
316
|
+
references.push(...fileRefs);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
walk(rootDir);
|
|
321
|
+
return { scannedFiles, references };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/analyzer.ts
|
|
325
|
+
var BUILTIN_ENV_VARS = /* @__PURE__ */ new Set([
|
|
326
|
+
"NODE_ENV",
|
|
327
|
+
"CI",
|
|
328
|
+
"MODE",
|
|
329
|
+
"DEV",
|
|
330
|
+
"PROD",
|
|
331
|
+
"SSR",
|
|
332
|
+
"BASE_URL"
|
|
333
|
+
]);
|
|
334
|
+
var PUBLIC_ENV_PREFIXES = [
|
|
335
|
+
"NEXT_PUBLIC_",
|
|
336
|
+
"VITE_",
|
|
337
|
+
"REACT_APP_",
|
|
338
|
+
"NUXT_PUBLIC_",
|
|
339
|
+
"PUBLIC_",
|
|
340
|
+
"EXPO_PUBLIC_",
|
|
341
|
+
"GATSBY_"
|
|
342
|
+
];
|
|
343
|
+
var SENSITIVE_KEYWORDS = [
|
|
344
|
+
"SECRET",
|
|
345
|
+
"PASSWORD",
|
|
346
|
+
"PASSWD",
|
|
347
|
+
"PRIVATE_KEY",
|
|
348
|
+
"PRIVATE",
|
|
349
|
+
"DATABASE_URL",
|
|
350
|
+
"DB_URL",
|
|
351
|
+
"DB_PASS",
|
|
352
|
+
"JWT_SECRET",
|
|
353
|
+
"AUTH_TOKEN",
|
|
354
|
+
"ACCESS_KEY",
|
|
355
|
+
"API_SECRET",
|
|
356
|
+
"SERVICE_ROLE",
|
|
357
|
+
"CREDENTIALS"
|
|
358
|
+
];
|
|
359
|
+
function detectSecretExposure(name) {
|
|
360
|
+
const upper = name.toUpperCase();
|
|
361
|
+
const prefix = PUBLIC_ENV_PREFIXES.find((p) => upper.startsWith(p));
|
|
362
|
+
if (!prefix) return null;
|
|
363
|
+
const rest = upper.slice(prefix.length);
|
|
364
|
+
const matchedKeyword = SENSITIVE_KEYWORDS.find((kw) => rest.includes(kw));
|
|
365
|
+
if (!matchedKeyword) return null;
|
|
366
|
+
return { prefix, matchedKeyword };
|
|
367
|
+
}
|
|
368
|
+
function auditEnv(options = {}) {
|
|
369
|
+
const rootDir = resolve(options.rootDir ?? process.cwd());
|
|
370
|
+
const envFileName = options.envFile ?? ".env";
|
|
371
|
+
const exampleFileName = options.exampleFile ?? ".env.example";
|
|
372
|
+
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
373
|
+
const { scannedFiles, references } = scanFiles(rootDir);
|
|
374
|
+
const usedInCode = {};
|
|
375
|
+
for (const ref of references) {
|
|
376
|
+
if (!usedInCode[ref.name]) {
|
|
377
|
+
usedInCode[ref.name] = [];
|
|
378
|
+
}
|
|
379
|
+
usedInCode[ref.name].push(ref);
|
|
380
|
+
}
|
|
381
|
+
const parsedEnv = parseEnvFile(resolve(rootDir, envFileName));
|
|
382
|
+
const parsedExample = parseEnvFile(resolve(rootDir, exampleFileName));
|
|
383
|
+
let envFileExists = parsedEnv.exists;
|
|
384
|
+
const localEnvKeys = new Set(parsedEnv.keys);
|
|
385
|
+
if (!options.envFile) {
|
|
386
|
+
const parsedLocal = parseEnvFile(resolve(rootDir, ".env.local"));
|
|
387
|
+
if (parsedLocal.exists) {
|
|
388
|
+
envFileExists = true;
|
|
389
|
+
}
|
|
390
|
+
for (const key of parsedLocal.keys) {
|
|
391
|
+
localEnvKeys.add(key);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
const exampleKeys = new Set(parsedExample.keys);
|
|
395
|
+
const codeKeys = Object.keys(usedInCode);
|
|
396
|
+
const codeKeySet = new Set(codeKeys);
|
|
397
|
+
const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
|
|
398
|
+
const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
|
|
399
|
+
const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
400
|
+
const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
401
|
+
const allKnownKeys = /* @__PURE__ */ new Set([
|
|
402
|
+
...codeKeys,
|
|
403
|
+
...localEnvKeys,
|
|
404
|
+
...exampleKeys
|
|
405
|
+
]);
|
|
406
|
+
const secretExposures = [];
|
|
407
|
+
for (const key of Array.from(allKnownKeys).sort()) {
|
|
408
|
+
if (ignoreSet.has(key)) continue;
|
|
409
|
+
const hit = detectSecretExposure(key);
|
|
410
|
+
if (hit) {
|
|
411
|
+
secretExposures.push({
|
|
412
|
+
name: key,
|
|
413
|
+
prefix: hit.prefix,
|
|
414
|
+
matchedKeyword: hit.matchedKeyword,
|
|
415
|
+
references: usedInCode[key] ?? []
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return {
|
|
420
|
+
rootDir,
|
|
421
|
+
scannedFiles,
|
|
422
|
+
envFileExists,
|
|
423
|
+
exampleFileExists: parsedExample.exists,
|
|
424
|
+
usedInCode,
|
|
425
|
+
missingInEnv,
|
|
426
|
+
missingInExample,
|
|
427
|
+
unusedInEnv,
|
|
428
|
+
unusedInExample,
|
|
429
|
+
secretExposures,
|
|
430
|
+
duplicateKeys: {
|
|
431
|
+
env: parsedEnv.duplicates,
|
|
432
|
+
example: parsedExample.duplicates
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/reporter.ts
|
|
438
|
+
import pc from "picocolors";
|
|
439
|
+
function formatRefs(refs) {
|
|
440
|
+
if (!refs || refs.length === 0) return "";
|
|
441
|
+
const shown = refs.slice(0, 2).map((r) => `${r.file}:${r.line}`);
|
|
442
|
+
const extra = refs.length > 2 ? ` (+${refs.length - 2} more)` : "";
|
|
443
|
+
return pc.dim(` \u2190 ${shown.join(", ")}${extra}`);
|
|
444
|
+
}
|
|
445
|
+
function hasBlockingIssues(result, options = {}) {
|
|
446
|
+
const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
|
|
447
|
+
return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0;
|
|
448
|
+
}
|
|
449
|
+
function formatAuditReport(result, options = {}) {
|
|
450
|
+
const envFile = options.envFile ?? ".env";
|
|
451
|
+
const exampleFile = options.exampleFile ?? ".env.example";
|
|
452
|
+
const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
|
|
453
|
+
const lines = [];
|
|
454
|
+
lines.push("");
|
|
455
|
+
lines.push(
|
|
456
|
+
`${pc.bold(pc.cyan("env-drift"))} ${pc.dim(
|
|
457
|
+
`\u2014 scanned ${result.scannedFiles} file${result.scannedFiles === 1 ? "" : "s"}`
|
|
458
|
+
)}`
|
|
459
|
+
);
|
|
460
|
+
lines.push("");
|
|
461
|
+
const totalIssues = result.secretExposures.length + (skipMissingInEnv ? 0 : result.missingInEnv.length) + result.missingInExample.length + result.unusedInEnv.length + result.unusedInExample.length + result.duplicateKeys.env.length + result.duplicateKeys.example.length;
|
|
462
|
+
if (totalIssues === 0) {
|
|
463
|
+
lines.push(pc.green("\u2714 No environment drift detected. Everything is in sync!"));
|
|
464
|
+
if (skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
465
|
+
lines.push(
|
|
466
|
+
pc.dim(` (No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode)`)
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
lines.push("");
|
|
470
|
+
return lines.join("\n");
|
|
471
|
+
}
|
|
472
|
+
if (result.secretExposures.length > 0) {
|
|
473
|
+
lines.push(pc.bold(pc.red(`\u2716 Possible Public Secret Exposure (${result.secretExposures.length})`)));
|
|
474
|
+
for (const item of result.secretExposures) {
|
|
475
|
+
lines.push(
|
|
476
|
+
` ${pc.red("\u2022")} ${pc.bold(item.name)} ${pc.dim(
|
|
477
|
+
`(public prefix "${item.prefix}" + sensitive "${item.matchedKeyword}")`
|
|
478
|
+
)}${formatRefs(item.references)}`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
lines.push("");
|
|
482
|
+
}
|
|
483
|
+
if (!skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
484
|
+
lines.push(pc.bold(pc.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
|
|
485
|
+
for (const key of result.missingInEnv) {
|
|
486
|
+
lines.push(` ${pc.red("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
|
|
487
|
+
}
|
|
488
|
+
lines.push("");
|
|
489
|
+
} else if (skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
490
|
+
lines.push(
|
|
491
|
+
pc.dim(`\u2139 No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode`)
|
|
492
|
+
);
|
|
493
|
+
lines.push("");
|
|
494
|
+
}
|
|
495
|
+
if (result.missingInExample.length > 0) {
|
|
496
|
+
lines.push(pc.bold(pc.yellow(`\u26A0 Missing in ${exampleFile} (${result.missingInExample.length})`)));
|
|
497
|
+
for (const key of result.missingInExample) {
|
|
498
|
+
lines.push(` ${pc.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
|
|
499
|
+
}
|
|
500
|
+
lines.push("");
|
|
501
|
+
}
|
|
502
|
+
if (result.unusedInEnv.length > 0) {
|
|
503
|
+
lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
|
|
504
|
+
for (const key of result.unusedInEnv) {
|
|
505
|
+
lines.push(` ${pc.dim("\u2022")} ${key}`);
|
|
506
|
+
}
|
|
507
|
+
lines.push("");
|
|
508
|
+
}
|
|
509
|
+
if (result.unusedInExample.length > 0) {
|
|
510
|
+
lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${exampleFile} (${result.unusedInExample.length})`)));
|
|
511
|
+
for (const key of result.unusedInExample) {
|
|
512
|
+
lines.push(` ${pc.dim("\u2022")} ${key}`);
|
|
513
|
+
}
|
|
514
|
+
lines.push("");
|
|
515
|
+
}
|
|
516
|
+
if (result.duplicateKeys.env.length > 0 || result.duplicateKeys.example.length > 0) {
|
|
517
|
+
lines.push(pc.bold(pc.yellow("\u26A0 Duplicate Keys")));
|
|
518
|
+
for (const key of result.duplicateKeys.env) {
|
|
519
|
+
lines.push(` ${pc.yellow("\u2022")} ${key} ${pc.dim(`in ${envFile}`)}`);
|
|
520
|
+
}
|
|
521
|
+
for (const key of result.duplicateKeys.example) {
|
|
522
|
+
lines.push(` ${pc.yellow("\u2022")} ${key} ${pc.dim(`in ${exampleFile}`)}`);
|
|
523
|
+
}
|
|
524
|
+
lines.push("");
|
|
525
|
+
}
|
|
526
|
+
if (result.missingInExample.length > 0) {
|
|
527
|
+
lines.push(
|
|
528
|
+
pc.dim(`Tip: Run with ${pc.white("--sync")} to safely append missing keys to ${exampleFile}.`)
|
|
529
|
+
);
|
|
530
|
+
lines.push("");
|
|
531
|
+
}
|
|
532
|
+
return lines.join("\n");
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// src/typegen.ts
|
|
536
|
+
import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
|
|
537
|
+
import { dirname } from "path";
|
|
538
|
+
function generateEnvTypes(result) {
|
|
539
|
+
const processKeys = /* @__PURE__ */ new Set();
|
|
540
|
+
const importMetaKeys = /* @__PURE__ */ new Set();
|
|
541
|
+
for (const [key, refs] of Object.entries(result.usedInCode)) {
|
|
542
|
+
if (BUILTIN_ENV_VARS.has(key)) continue;
|
|
543
|
+
for (const ref of refs) {
|
|
544
|
+
if (ref.source === "import.meta.env") {
|
|
545
|
+
importMetaKeys.add(key);
|
|
546
|
+
} else {
|
|
547
|
+
processKeys.add(key);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
for (const key of result.unusedInExample) {
|
|
552
|
+
if (!BUILTIN_ENV_VARS.has(key) && !importMetaKeys.has(key)) {
|
|
553
|
+
processKeys.add(key);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const lines = [
|
|
557
|
+
"// Auto-generated by env-drift. Do not edit manually.",
|
|
558
|
+
""
|
|
559
|
+
];
|
|
560
|
+
const sortedProcess = Array.from(processKeys).sort();
|
|
561
|
+
if (sortedProcess.length > 0) {
|
|
562
|
+
lines.push("declare namespace NodeJS {");
|
|
563
|
+
lines.push(" interface ProcessEnv {");
|
|
564
|
+
for (const key of sortedProcess) {
|
|
565
|
+
lines.push(` ${key}: string;`);
|
|
566
|
+
}
|
|
567
|
+
lines.push(" }");
|
|
568
|
+
lines.push("}");
|
|
569
|
+
lines.push("");
|
|
570
|
+
}
|
|
571
|
+
const sortedMeta = Array.from(importMetaKeys).sort();
|
|
572
|
+
if (sortedMeta.length > 0) {
|
|
573
|
+
lines.push("interface ImportMetaEnv {");
|
|
574
|
+
for (const key of sortedMeta) {
|
|
575
|
+
lines.push(` readonly ${key}: string;`);
|
|
576
|
+
}
|
|
577
|
+
lines.push("}");
|
|
578
|
+
lines.push("");
|
|
579
|
+
lines.push("interface ImportMeta {");
|
|
580
|
+
lines.push(" readonly env: ImportMetaEnv;");
|
|
581
|
+
lines.push("}");
|
|
582
|
+
lines.push("");
|
|
583
|
+
}
|
|
584
|
+
if (sortedProcess.length === 0 && sortedMeta.length === 0) {
|
|
585
|
+
lines.push("// No environment variables detected.");
|
|
586
|
+
lines.push("");
|
|
587
|
+
}
|
|
588
|
+
return lines.join("\n");
|
|
589
|
+
}
|
|
590
|
+
function writeEnvTypes(outputPath, result) {
|
|
591
|
+
const content = generateEnvTypes(result);
|
|
592
|
+
mkdirSync(dirname(outputPath), { recursive: true });
|
|
593
|
+
writeFileSync2(outputPath, content, "utf-8");
|
|
594
|
+
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
595
|
+
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
596
|
+
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
597
|
+
]);
|
|
598
|
+
return { outputPath, count: uniqueKeys.size };
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/cli.ts
|
|
602
|
+
var VERSION = package_default.version;
|
|
603
|
+
var HELP_TEXT = `
|
|
604
|
+
${pc2.bold(pc2.cyan("@subramanyaks/env-drift"))} v${VERSION} \u2014 Detect environment variable drift and public secret leaks
|
|
605
|
+
|
|
606
|
+
${pc2.bold("Usage:")}
|
|
607
|
+
npx @subramanyaks/env-drift [options]
|
|
608
|
+
|
|
609
|
+
${pc2.bold("Options:")}
|
|
610
|
+
-d, --dir <path> Project directory to scan (default: ".")
|
|
611
|
+
--env <file> Local env file name (default: ".env")
|
|
612
|
+
--example <file> Example env file name (default: ".env.example")
|
|
613
|
+
--ignore <vars> Comma-separated env var names to ignore
|
|
614
|
+
--sync Safely append missing keys to .env.example as KEY=
|
|
615
|
+
--types Generate env.d.ts for detected env variables
|
|
616
|
+
--types-out <path> Output path for --types (default: "env.d.ts")
|
|
617
|
+
--ci Exit with code 1 if missing vars or secret leaks are found
|
|
618
|
+
--json Output audit results as JSON
|
|
619
|
+
-v, --version Show version
|
|
620
|
+
-h, --help Show this help message
|
|
621
|
+
`;
|
|
622
|
+
function runCli(argv = process.argv.slice(2)) {
|
|
623
|
+
let values;
|
|
624
|
+
try {
|
|
625
|
+
const parsed = parseArgs({
|
|
626
|
+
args: argv,
|
|
627
|
+
options: {
|
|
628
|
+
dir: { type: "string", short: "d" },
|
|
629
|
+
env: { type: "string" },
|
|
630
|
+
example: { type: "string" },
|
|
631
|
+
ignore: { type: "string" },
|
|
632
|
+
sync: { type: "boolean", default: false },
|
|
633
|
+
types: { type: "boolean", default: false },
|
|
634
|
+
"types-out": { type: "string" },
|
|
635
|
+
ci: { type: "boolean", default: false },
|
|
636
|
+
json: { type: "boolean", default: false },
|
|
637
|
+
version: { type: "boolean", short: "v", default: false },
|
|
638
|
+
help: { type: "boolean", short: "h", default: false }
|
|
639
|
+
},
|
|
640
|
+
strict: true
|
|
641
|
+
});
|
|
642
|
+
values = parsed.values;
|
|
643
|
+
} catch (err) {
|
|
644
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
645
|
+
console.error(pc2.red(`Error: ${msg}`));
|
|
646
|
+
console.error(pc2.dim("Run `env-drift --help` for usage."));
|
|
647
|
+
return 1;
|
|
648
|
+
}
|
|
649
|
+
if (values.help) {
|
|
650
|
+
console.log(HELP_TEXT);
|
|
651
|
+
return 0;
|
|
652
|
+
}
|
|
653
|
+
if (values.version) {
|
|
654
|
+
console.log(VERSION);
|
|
655
|
+
return 0;
|
|
656
|
+
}
|
|
657
|
+
const rootDir = resolve2(typeof values.dir === "string" ? values.dir : process.cwd());
|
|
658
|
+
const envFile = typeof values.env === "string" ? values.env : void 0;
|
|
659
|
+
const exampleFile = typeof values.example === "string" ? values.example : ".env.example";
|
|
660
|
+
const ignore = typeof values.ignore === "string" ? values.ignore.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
|
|
661
|
+
const result = auditEnv({
|
|
662
|
+
rootDir,
|
|
663
|
+
envFile,
|
|
664
|
+
exampleFile,
|
|
665
|
+
ignore
|
|
666
|
+
});
|
|
667
|
+
if (values.sync && result.missingInExample.length > 0) {
|
|
668
|
+
const examplePath = resolve2(rootDir, exampleFile);
|
|
669
|
+
const synced = syncEnvExample(examplePath, result.missingInExample);
|
|
670
|
+
if (synced.added.length > 0) {
|
|
671
|
+
const addedSet = new Set(synced.added);
|
|
672
|
+
result.missingInExample = result.missingInExample.filter((k) => !addedSet.has(k));
|
|
673
|
+
result.exampleFileExists = true;
|
|
674
|
+
if (!values.json) {
|
|
675
|
+
const action = synced.created ? "Created" : "Updated";
|
|
676
|
+
console.log(
|
|
677
|
+
pc2.green(`\u2714 ${action} ${exampleFile} with ${synced.added.length} key(s): ${synced.added.join(", ")}`)
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (values.types || typeof values["types-out"] === "string") {
|
|
683
|
+
const outFile = typeof values["types-out"] === "string" ? values["types-out"] : "env.d.ts";
|
|
684
|
+
const outputPath = resolve2(rootDir, outFile);
|
|
685
|
+
const generated = writeEnvTypes(outputPath, result);
|
|
686
|
+
if (!values.json) {
|
|
687
|
+
console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
if (values.json) {
|
|
691
|
+
console.log(JSON.stringify(result, null, 2));
|
|
692
|
+
} else {
|
|
693
|
+
console.log(
|
|
694
|
+
formatAuditReport(result, {
|
|
695
|
+
envFile: envFile ?? ".env",
|
|
696
|
+
exampleFile,
|
|
697
|
+
ci: Boolean(values.ci)
|
|
698
|
+
})
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
if (values.ci && hasBlockingIssues(result)) {
|
|
702
|
+
return 1;
|
|
703
|
+
}
|
|
704
|
+
return 0;
|
|
705
|
+
}
|
|
706
|
+
function isDirectExecution() {
|
|
707
|
+
const entry = process.argv[1];
|
|
708
|
+
if (!entry) return false;
|
|
709
|
+
try {
|
|
710
|
+
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
|
711
|
+
} catch {
|
|
712
|
+
return entry.endsWith("cli.js") || entry.endsWith("env-drift") || entry.endsWith("env-drift-cli");
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
if (isDirectExecution()) {
|
|
716
|
+
process.exitCode = runCli();
|
|
717
|
+
}
|
|
718
|
+
export {
|
|
719
|
+
runCli
|
|
720
|
+
};
|