@subramanyaks/env-drift 1.0.0 → 1.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/dist/cli.js CHANGED
@@ -1,10 +1,84 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { resolve as resolve2 } from "path";
4
+ import { realpathSync } from "fs";
5
+ import { resolve as resolve3 } from "path";
6
+ import { fileURLToPath } from "url";
5
7
  import { parseArgs } from "util";
6
8
  import pc2 from "picocolors";
7
9
 
10
+ // package.json
11
+ var package_default = {
12
+ name: "@subramanyaks/env-drift",
13
+ version: "1.1.0",
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
+ "CHANGELOG.md",
36
+ "LICENSE"
37
+ ],
38
+ engines: {
39
+ node: ">=18.17.0"
40
+ },
41
+ scripts: {
42
+ dev: "tsup --watch",
43
+ build: "tsup",
44
+ typecheck: "tsc --noEmit",
45
+ test: "vitest run",
46
+ "test:watch": "vitest",
47
+ prepublishOnly: "npm run typecheck && npm test && npm run build"
48
+ },
49
+ repository: {
50
+ type: "git",
51
+ url: "https://github.com/SubramanyaKS/env-drift.git"
52
+ },
53
+ bugs: {
54
+ url: "https://github.com/SubramanyaKS/env-drift/issues"
55
+ },
56
+ keywords: [
57
+ "env",
58
+ "dotenv",
59
+ "env-drift",
60
+ "environment",
61
+ "cli",
62
+ "security",
63
+ "audit",
64
+ "typescript",
65
+ "ci",
66
+ "nextjs",
67
+ "vite"
68
+ ],
69
+ author: "SubramanyaKS",
70
+ license: "MIT",
71
+ dependencies: {
72
+ picocolors: "^1.1.1"
73
+ },
74
+ devDependencies: {
75
+ "@types/node": "^22.20.7",
76
+ tsup: "^8.5.1",
77
+ typescript: "^5.9.3",
78
+ vitest: "^4.0.18"
79
+ }
80
+ };
81
+
8
82
  // src/analyzer.ts
9
83
  import { resolve } from "path";
10
84
 
@@ -15,8 +89,27 @@ function parseValue(raw) {
15
89
  const trimmed = raw.trim();
16
90
  if (!trimmed) return "";
17
91
  const quote = trimmed[0];
18
- if (quote === '"' || quote === "'") {
19
- const closingIdx = trimmed.indexOf(quote, 1);
92
+ if (quote === '"') {
93
+ let result = "";
94
+ for (let i = 1; i < trimmed.length; i++) {
95
+ const ch = trimmed[i];
96
+ if (ch === "\\" && i + 1 < trimmed.length) {
97
+ const next = trimmed[i + 1];
98
+ if (next === "n") result += "\n";
99
+ else if (next === "r") result += "\r";
100
+ else if (next === "t") result += " ";
101
+ else result += next;
102
+ i++;
103
+ } else if (ch === '"') {
104
+ return result;
105
+ } else {
106
+ result += ch;
107
+ }
108
+ }
109
+ return result;
110
+ }
111
+ if (quote === "'") {
112
+ const closingIdx = trimmed.indexOf("'", 1);
20
113
  if (closingIdx !== -1) {
21
114
  return trimmed.slice(1, closingIdx);
22
115
  }
@@ -33,8 +126,10 @@ function parseEnvContent(content) {
33
126
  const seen = /* @__PURE__ */ new Set();
34
127
  const duplicateSet = /* @__PURE__ */ new Set();
35
128
  const values = {};
129
+ const keyLines = {};
36
130
  const lines = content.split(/\r?\n/);
37
- for (const rawLine of lines) {
131
+ for (let i = 0; i < lines.length; i++) {
132
+ const rawLine = lines[i];
38
133
  const line = rawLine.trim();
39
134
  if (!line || line.startsWith("#")) continue;
40
135
  const match = ENV_LINE_REGEX.exec(line);
@@ -49,10 +144,12 @@ function parseEnvContent(content) {
49
144
  keys.push(key);
50
145
  }
51
146
  values[key] = parseValue(rawValue);
147
+ keyLines[key] = i + 1;
52
148
  }
53
149
  return {
54
150
  keys,
55
151
  values,
152
+ lines: keyLines,
56
153
  duplicates: Array.from(duplicateSet)
57
154
  };
58
155
  }
@@ -63,16 +160,18 @@ function parseEnvFile(filePath) {
63
160
  exists: false,
64
161
  keys: [],
65
162
  values: {},
163
+ lines: {},
66
164
  duplicates: []
67
165
  };
68
166
  }
69
167
  const content = readFileSync(filePath, "utf-8");
70
- const { keys, values, duplicates } = parseEnvContent(content);
168
+ const { keys, values, lines, duplicates } = parseEnvContent(content);
71
169
  return {
72
170
  filePath,
73
171
  exists: true,
74
172
  keys,
75
173
  values,
174
+ lines,
76
175
  duplicates
77
176
  };
78
177
  }
@@ -144,35 +243,48 @@ function getLineNumber(source, index) {
144
243
  }
145
244
  return line;
146
245
  }
246
+ function collectIgnoredLines(source) {
247
+ const ignored = /* @__PURE__ */ new Set();
248
+ const lines = source.split(/\r?\n/);
249
+ for (let i = 0; i < lines.length; i++) {
250
+ const line = lines[i];
251
+ if (/(?:\/\/|\/\*)\s*env-drift-ignore-next-line\b/.test(line)) {
252
+ ignored.add(i + 2);
253
+ } else if (/(?:\/\/|\/\*)\s*env-drift-ignore\b/.test(line)) {
254
+ ignored.add(i + 1);
255
+ }
256
+ }
257
+ return ignored;
258
+ }
147
259
  function extractEnvReferences(content, filePath) {
260
+ const ignoredLines = collectIgnoredLines(content);
148
261
  const cleaned = stripCommentsPreservingLines(content);
149
262
  const refs = [];
150
263
  const normalizedFile = filePath.replace(/\\/g, "/");
151
- const dotRegex = /\b(process\.env|import\.meta\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
152
- for (const match of cleaned.matchAll(dotRegex)) {
153
- const source = match[1];
154
- const name = match[2];
155
- if (!name || match.index === void 0) continue;
264
+ const addRef = (name, line, source) => {
265
+ if (ignoredLines.has(line)) return;
156
266
  refs.push({
157
267
  name,
158
268
  file: normalizedFile,
159
- line: getLineNumber(cleaned, match.index),
269
+ line,
160
270
  source
161
271
  });
272
+ };
273
+ const dotRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
274
+ for (const match of cleaned.matchAll(dotRegex)) {
275
+ const source = match[1];
276
+ const name = match[2];
277
+ if (!name || match.index === void 0) continue;
278
+ addRef(name, getLineNumber(cleaned, match.index), source);
162
279
  }
163
- const bracketRegex = /\b(process\.env|import\.meta\.env)\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
280
+ const bracketRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
164
281
  for (const match of cleaned.matchAll(bracketRegex)) {
165
282
  const source = match[1];
166
283
  const name = match[2];
167
284
  if (!name || match.index === void 0) continue;
168
- refs.push({
169
- name,
170
- file: normalizedFile,
171
- line: getLineNumber(cleaned, match.index),
172
- source
173
- });
285
+ addRef(name, getLineNumber(cleaned, match.index), source);
174
286
  }
175
- const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
287
+ const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env|Bun\.env)\b/g;
176
288
  for (const match of cleaned.matchAll(destructureRegex)) {
177
289
  const body = match[1];
178
290
  const source = match[2];
@@ -189,14 +301,15 @@ function extractEnvReferences(content, filePath) {
189
301
  if (!name) continue;
190
302
  const leadingWs = part.indexOf(name);
191
303
  const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
192
- refs.push({
193
- name,
194
- file: normalizedFile,
195
- line: getLineNumber(cleaned, absoluteIdx),
196
- source
197
- });
304
+ addRef(name, getLineNumber(cleaned, absoluteIdx), source);
198
305
  }
199
306
  }
307
+ const denoRegex = /\bDeno\.env\s*\??\.\s*get\s*\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\)/g;
308
+ for (const match of cleaned.matchAll(denoRegex)) {
309
+ const name = match[1];
310
+ if (!name || match.index === void 0) continue;
311
+ addRef(name, getLineNumber(cleaned, match.index), "Deno.env");
312
+ }
200
313
  refs.sort((a, b) => a.line - b.line);
201
314
  return refs;
202
315
  }
@@ -264,12 +377,87 @@ var SENSITIVE_KEYWORDS = [
264
377
  "SERVICE_ROLE",
265
378
  "CREDENTIALS"
266
379
  ];
267
- function detectSecretExposure(name) {
380
+ var PLACEHOLDER_VALUE_PATTERNS = [
381
+ /^your[_-]/i,
382
+ /^my[_-]/i,
383
+ /^change[_-]?me$/i,
384
+ /^replace[_-]?me$/i,
385
+ /^placeholder$/i,
386
+ /^example$/i,
387
+ /^dummy$/i,
388
+ /^test$/i,
389
+ /^todo$/i,
390
+ /^<[^>]+>$/,
391
+ /^\$\{[^}]+\}$/,
392
+ /^[xX*]{4,}$/
393
+ ];
394
+ var PLACEHOLDER_URL_PASSWORDS = /* @__PURE__ */ new Set([
395
+ "password",
396
+ "pass",
397
+ "passwd",
398
+ "postgres",
399
+ "root",
400
+ "admin",
401
+ "changeme",
402
+ "change_me",
403
+ "secret",
404
+ "example",
405
+ "dummy",
406
+ "test",
407
+ "1234",
408
+ "123456",
409
+ "your_password",
410
+ "<password>"
411
+ ]);
412
+ var EXAMPLE_SECRET_PATTERNS = [
413
+ { pattern: /^sk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe live secret key" },
414
+ { pattern: /^rk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe restricted live key" },
415
+ { pattern: /^whsec_[A-Za-z0-9]{16,}$/, reason: "Stripe webhook secret" },
416
+ { pattern: /^gh[pous]_[A-Za-z0-9]{20,}$/, reason: "GitHub access token" },
417
+ { pattern: /^github_pat_[A-Za-z0-9_]{20,}$/, reason: "GitHub fine-grained token" },
418
+ { pattern: /^AKIA[0-9A-Z]{16}$/, reason: "AWS Access Key ID" },
419
+ { pattern: /^sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}$/, reason: "AI provider API key" },
420
+ { pattern: /^sk-[A-Za-z0-9]{32,}$/, reason: "Secret API key (sk-...)" },
421
+ { pattern: /^xox[baprs]-[A-Za-z0-9-]{10,}$/, reason: "Slack token" },
422
+ { pattern: /^AIza[0-9A-Za-z_-]{35}$/, reason: "Google API key" },
423
+ {
424
+ pattern: /^eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}$/,
425
+ reason: "JWT token"
426
+ },
427
+ {
428
+ pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
429
+ reason: "PEM private key"
430
+ }
431
+ ];
432
+ var CONNECTION_URL_PASSWORD_REGEX = /^(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^:\s/]+:([^@\s/]+)@/i;
433
+ function detectExampleSecretLeak(_name, value) {
434
+ const trimmed = value.trim();
435
+ if (!trimmed) return null;
436
+ if (PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(trimmed))) {
437
+ return null;
438
+ }
439
+ for (const { pattern, reason } of EXAMPLE_SECRET_PATTERNS) {
440
+ if (pattern.test(trimmed)) {
441
+ return reason;
442
+ }
443
+ }
444
+ const urlMatch = CONNECTION_URL_PASSWORD_REGEX.exec(trimmed);
445
+ if (urlMatch) {
446
+ const password = urlMatch[1] ?? "";
447
+ if (password && !PLACEHOLDER_URL_PASSWORDS.has(password.toLowerCase()) && !PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(password))) {
448
+ return "Connection URL with embedded password";
449
+ }
450
+ }
451
+ return null;
452
+ }
453
+ function detectSecretExposure(name, options) {
268
454
  const upper = name.toUpperCase();
269
- const prefix = PUBLIC_ENV_PREFIXES.find((p) => upper.startsWith(p));
455
+ const prefixes = options?.publicPrefixes?.length ? [...PUBLIC_ENV_PREFIXES, ...options.publicPrefixes.map((p) => p.toUpperCase())] : PUBLIC_ENV_PREFIXES;
456
+ const keywords = options?.sensitiveKeywords?.length ? [...SENSITIVE_KEYWORDS, ...options.sensitiveKeywords.map((k) => k.toUpperCase())] : SENSITIVE_KEYWORDS;
457
+ const prefix = prefixes.find((p) => upper.startsWith(p));
270
458
  if (!prefix) return null;
271
459
  const rest = upper.slice(prefix.length);
272
- const matchedKeyword = SENSITIVE_KEYWORDS.find((kw) => rest.includes(kw));
460
+ const matchedKeyword = keywords.find((kw) => rest.includes(kw));
273
461
  if (!matchedKeyword) return null;
274
462
  return { prefix, matchedKeyword };
275
463
  }
@@ -278,7 +466,8 @@ function auditEnv(options = {}) {
278
466
  const envFileName = options.envFile ?? ".env";
279
467
  const exampleFileName = options.exampleFile ?? ".env.example";
280
468
  const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
281
- const { scannedFiles, references } = scanFiles(rootDir);
469
+ const ignoreDirs = options.ignoreDirs?.length ? [...DEFAULT_IGNORE_DIRS, ...options.ignoreDirs] : void 0;
470
+ const { scannedFiles, references } = scanFiles(rootDir, { ignoreDirs });
282
471
  const usedInCode = {};
283
472
  for (const ref of references) {
284
473
  if (!usedInCode[ref.name]) {
@@ -288,11 +477,17 @@ function auditEnv(options = {}) {
288
477
  }
289
478
  const parsedEnv = parseEnvFile(resolve(rootDir, envFileName));
290
479
  const parsedExample = parseEnvFile(resolve(rootDir, exampleFileName));
480
+ let envFileExists = parsedEnv.exists;
291
481
  const localEnvKeys = new Set(parsedEnv.keys);
482
+ const localEnvValues = { ...parsedEnv.values };
292
483
  if (!options.envFile) {
293
484
  const parsedLocal = parseEnvFile(resolve(rootDir, ".env.local"));
485
+ if (parsedLocal.exists) {
486
+ envFileExists = true;
487
+ }
294
488
  for (const key of parsedLocal.keys) {
295
489
  localEnvKeys.add(key);
490
+ localEnvValues[key] = parsedLocal.values[key] ?? "";
296
491
  }
297
492
  }
298
493
  const exampleKeys = new Set(parsedExample.keys);
@@ -300,6 +495,9 @@ function auditEnv(options = {}) {
300
495
  const codeKeySet = new Set(codeKeys);
301
496
  const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
302
497
  const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
498
+ const emptyInEnv = codeKeys.filter(
499
+ (k) => !ignoreSet.has(k) && localEnvKeys.has(k) && (localEnvValues[k] ?? "").trim() === ""
500
+ ).sort();
303
501
  const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
304
502
  const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
305
503
  const allKnownKeys = /* @__PURE__ */ new Set([
@@ -310,7 +508,10 @@ function auditEnv(options = {}) {
310
508
  const secretExposures = [];
311
509
  for (const key of Array.from(allKnownKeys).sort()) {
312
510
  if (ignoreSet.has(key)) continue;
313
- const hit = detectSecretExposure(key);
511
+ const hit = detectSecretExposure(key, {
512
+ publicPrefixes: options.publicPrefixes,
513
+ sensitiveKeywords: options.sensitiveKeywords
514
+ });
314
515
  if (hit) {
315
516
  secretExposures.push({
316
517
  name: key,
@@ -320,15 +521,32 @@ function auditEnv(options = {}) {
320
521
  });
321
522
  }
322
523
  }
524
+ const exampleSecretLeaks = [];
525
+ for (const key of [...parsedExample.keys].sort()) {
526
+ if (ignoreSet.has(key)) continue;
527
+ const reason = detectExampleSecretLeak(key, parsedExample.values[key] ?? "");
528
+ if (reason) {
529
+ exampleSecretLeaks.push({
530
+ name: key,
531
+ reason,
532
+ file: exampleFileName,
533
+ line: parsedExample.lines[key] ?? 1
534
+ });
535
+ }
536
+ }
323
537
  return {
324
538
  rootDir,
325
539
  scannedFiles,
540
+ envFileExists,
541
+ exampleFileExists: parsedExample.exists,
326
542
  usedInCode,
327
543
  missingInEnv,
328
544
  missingInExample,
545
+ emptyInEnv,
329
546
  unusedInEnv,
330
547
  unusedInExample,
331
548
  secretExposures,
549
+ exampleSecretLeaks,
332
550
  duplicateKeys: {
333
551
  env: parsedEnv.duplicates,
334
552
  example: parsedExample.duplicates
@@ -336,6 +554,57 @@ function auditEnv(options = {}) {
336
554
  };
337
555
  }
338
556
 
557
+ // src/config.ts
558
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
559
+ import { resolve as resolve2 } from "path";
560
+ function toStringArray(val) {
561
+ if (!Array.isArray(val)) return void 0;
562
+ return val.filter((item) => typeof item === "string" && item.trim().length > 0);
563
+ }
564
+ function normalizeConfig(raw) {
565
+ if (!raw || typeof raw !== "object") return {};
566
+ const obj = raw;
567
+ const config = {};
568
+ if (typeof obj.envFile === "string" && obj.envFile.trim()) {
569
+ config.envFile = obj.envFile.trim();
570
+ }
571
+ if (typeof obj.exampleFile === "string" && obj.exampleFile.trim()) {
572
+ config.exampleFile = obj.exampleFile.trim();
573
+ }
574
+ const ignore = toStringArray(obj.ignore);
575
+ if (ignore) config.ignore = ignore;
576
+ const ignoreDirs = toStringArray(obj.ignoreDirs);
577
+ if (ignoreDirs) config.ignoreDirs = ignoreDirs;
578
+ const publicPrefixes = toStringArray(obj.publicPrefixes);
579
+ if (publicPrefixes) config.publicPrefixes = publicPrefixes;
580
+ const sensitiveKeywords = toStringArray(obj.sensitiveKeywords);
581
+ if (sensitiveKeywords) config.sensitiveKeywords = sensitiveKeywords;
582
+ return config;
583
+ }
584
+ function loadConfig(rootDir) {
585
+ const rcPath = resolve2(rootDir, ".envdriftrc.json");
586
+ if (existsSync2(rcPath)) {
587
+ try {
588
+ const parsed = JSON.parse(readFileSync3(rcPath, "utf-8"));
589
+ return normalizeConfig(parsed);
590
+ } catch (err) {
591
+ const msg = err instanceof Error ? err.message : String(err);
592
+ throw new Error(`Failed to parse .envdriftrc.json: ${msg}`);
593
+ }
594
+ }
595
+ const pkgPath = resolve2(rootDir, "package.json");
596
+ if (existsSync2(pkgPath)) {
597
+ try {
598
+ const parsed = JSON.parse(readFileSync3(pkgPath, "utf-8"));
599
+ if (parsed && typeof parsed === "object" && parsed["env-drift"]) {
600
+ return normalizeConfig(parsed["env-drift"]);
601
+ }
602
+ } catch {
603
+ }
604
+ }
605
+ return {};
606
+ }
607
+
339
608
  // src/reporter.ts
340
609
  import pc from "picocolors";
341
610
  function formatRefs(refs) {
@@ -344,12 +613,14 @@ function formatRefs(refs) {
344
613
  const extra = refs.length > 2 ? ` (+${refs.length - 2} more)` : "";
345
614
  return pc.dim(` \u2190 ${shown.join(", ")}${extra}`);
346
615
  }
347
- function hasBlockingIssues(result) {
348
- return result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0;
616
+ function hasBlockingIssues(result, options = {}) {
617
+ const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
618
+ return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
349
619
  }
350
620
  function formatAuditReport(result, options = {}) {
351
621
  const envFile = options.envFile ?? ".env";
352
622
  const exampleFile = options.exampleFile ?? ".env.example";
623
+ const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
353
624
  const lines = [];
354
625
  lines.push("");
355
626
  lines.push(
@@ -358,9 +629,14 @@ function formatAuditReport(result, options = {}) {
358
629
  )}`
359
630
  );
360
631
  lines.push("");
361
- const totalIssues = result.secretExposures.length + result.missingInEnv.length + result.missingInExample.length + result.unusedInEnv.length + result.unusedInExample.length + result.duplicateKeys.env.length + result.duplicateKeys.example.length;
632
+ const totalIssues = result.secretExposures.length + result.exampleSecretLeaks.length + (skipMissingInEnv ? 0 : result.missingInEnv.length) + result.missingInExample.length + result.emptyInEnv.length + result.unusedInEnv.length + result.unusedInExample.length + result.duplicateKeys.env.length + result.duplicateKeys.example.length;
362
633
  if (totalIssues === 0) {
363
634
  lines.push(pc.green("\u2714 No environment drift detected. Everything is in sync!"));
635
+ if (skipMissingInEnv && result.missingInEnv.length > 0) {
636
+ lines.push(
637
+ pc.dim(` (No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode)`)
638
+ );
639
+ }
364
640
  lines.push("");
365
641
  return lines.join("\n");
366
642
  }
@@ -375,12 +651,30 @@ function formatAuditReport(result, options = {}) {
375
651
  }
376
652
  lines.push("");
377
653
  }
378
- if (result.missingInEnv.length > 0) {
654
+ if (result.exampleSecretLeaks.length > 0) {
655
+ lines.push(
656
+ pc.bold(pc.red(`\u2716 Possible Real Secret in ${exampleFile} (${result.exampleSecretLeaks.length})`))
657
+ );
658
+ for (const item of result.exampleSecretLeaks) {
659
+ lines.push(
660
+ ` ${pc.red("\u2022")} ${pc.bold(item.name)} ${pc.dim(
661
+ `(${item.reason}) \u2190 ${item.file}:${item.line}`
662
+ )}`
663
+ );
664
+ }
665
+ lines.push("");
666
+ }
667
+ if (!skipMissingInEnv && result.missingInEnv.length > 0) {
379
668
  lines.push(pc.bold(pc.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
380
669
  for (const key of result.missingInEnv) {
381
670
  lines.push(` ${pc.red("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
382
671
  }
383
672
  lines.push("");
673
+ } else if (skipMissingInEnv && result.missingInEnv.length > 0) {
674
+ lines.push(
675
+ pc.dim(`\u2139 No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode`)
676
+ );
677
+ lines.push("");
384
678
  }
385
679
  if (result.missingInExample.length > 0) {
386
680
  lines.push(pc.bold(pc.yellow(`\u26A0 Missing in ${exampleFile} (${result.missingInExample.length})`)));
@@ -389,6 +683,13 @@ function formatAuditReport(result, options = {}) {
389
683
  }
390
684
  lines.push("");
391
685
  }
686
+ if (result.emptyInEnv.length > 0) {
687
+ lines.push(pc.bold(pc.yellow(`\u26A0 Empty Value in ${envFile} (${result.emptyInEnv.length})`)));
688
+ for (const key of result.emptyInEnv) {
689
+ lines.push(` ${pc.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
690
+ }
691
+ lines.push("");
692
+ }
392
693
  if (result.unusedInEnv.length > 0) {
393
694
  lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
394
695
  for (const key of result.unusedInEnv) {
@@ -421,6 +722,127 @@ function formatAuditReport(result, options = {}) {
421
722
  }
422
723
  return lines.join("\n");
423
724
  }
725
+ function escapeGitHubData(value) {
726
+ return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
727
+ }
728
+ function escapeGitHubProperty(value) {
729
+ return escapeGitHubData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
730
+ }
731
+ function buildAnnotation(level, title, message, file, line) {
732
+ const props = [];
733
+ if (file) props.push(`file=${escapeGitHubProperty(file)}`);
734
+ if (line !== void 0) props.push(`line=${line}`);
735
+ props.push(`title=${escapeGitHubProperty(title)}`);
736
+ return `::${level} ${props.join(",")}::${escapeGitHubData(message)}`;
737
+ }
738
+ function formatGitHubAnnotations(result, options = {}) {
739
+ const envFile = options.envFile ?? ".env";
740
+ const exampleFile = options.exampleFile ?? ".env.example";
741
+ const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
742
+ const lines = [];
743
+ for (const item of result.secretExposures) {
744
+ const firstRef = item.references[0];
745
+ lines.push(
746
+ buildAnnotation(
747
+ "error",
748
+ "Public Secret Exposure",
749
+ `${item.name} uses client-exposed prefix "${item.prefix}" with sensitive keyword "${item.matchedKeyword}"`,
750
+ firstRef?.file,
751
+ firstRef?.line
752
+ )
753
+ );
754
+ }
755
+ for (const leak of result.exampleSecretLeaks) {
756
+ lines.push(
757
+ buildAnnotation(
758
+ "error",
759
+ `Secret Leak in ${exampleFile}`,
760
+ `${leak.name} appears to contain a real secret (${leak.reason}). Replace it with an empty placeholder.`,
761
+ leak.file,
762
+ leak.line
763
+ )
764
+ );
765
+ }
766
+ if (!skipMissingInEnv) {
767
+ for (const key of result.missingInEnv) {
768
+ const firstRef = result.usedInCode[key]?.[0];
769
+ lines.push(
770
+ buildAnnotation(
771
+ "error",
772
+ `Missing in ${envFile}`,
773
+ `Environment variable ${key} is referenced in code but missing in ${envFile}`,
774
+ firstRef?.file,
775
+ firstRef?.line
776
+ )
777
+ );
778
+ }
779
+ }
780
+ for (const key of result.missingInExample) {
781
+ const firstRef = result.usedInCode[key]?.[0];
782
+ lines.push(
783
+ buildAnnotation(
784
+ "error",
785
+ `Missing in ${exampleFile}`,
786
+ `Environment variable ${key} is referenced in code but missing in ${exampleFile}. Run \`env-drift --sync\` to update.`,
787
+ firstRef?.file,
788
+ firstRef?.line
789
+ )
790
+ );
791
+ }
792
+ for (const key of result.emptyInEnv) {
793
+ const firstRef = result.usedInCode[key]?.[0];
794
+ lines.push(
795
+ buildAnnotation(
796
+ "warning",
797
+ `Empty Value in ${envFile}`,
798
+ `Environment variable ${key} is defined in ${envFile} with an empty value`,
799
+ firstRef?.file,
800
+ firstRef?.line
801
+ )
802
+ );
803
+ }
804
+ for (const key of result.unusedInEnv) {
805
+ lines.push(
806
+ buildAnnotation(
807
+ "warning",
808
+ `Unused in ${envFile}`,
809
+ `Environment variable ${key} is defined in ${envFile} but not referenced in code`,
810
+ envFile
811
+ )
812
+ );
813
+ }
814
+ for (const key of result.unusedInExample) {
815
+ lines.push(
816
+ buildAnnotation(
817
+ "warning",
818
+ `Unused in ${exampleFile}`,
819
+ `Environment variable ${key} is defined in ${exampleFile} but not referenced in code`,
820
+ exampleFile
821
+ )
822
+ );
823
+ }
824
+ for (const key of result.duplicateKeys.env) {
825
+ lines.push(
826
+ buildAnnotation(
827
+ "warning",
828
+ `Duplicate Key in ${envFile}`,
829
+ `Environment variable ${key} is defined multiple times in ${envFile}`,
830
+ envFile
831
+ )
832
+ );
833
+ }
834
+ for (const key of result.duplicateKeys.example) {
835
+ lines.push(
836
+ buildAnnotation(
837
+ "warning",
838
+ `Duplicate Key in ${exampleFile}`,
839
+ `Environment variable ${key} is defined multiple times in ${exampleFile}`,
840
+ exampleFile
841
+ )
842
+ );
843
+ }
844
+ return lines.join("\n");
845
+ }
424
846
 
425
847
  // src/typegen.ts
426
848
  import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
@@ -489,7 +911,7 @@ function writeEnvTypes(outputPath, result) {
489
911
  }
490
912
 
491
913
  // src/cli.ts
492
- var VERSION = "1.0.0";
914
+ var VERSION = package_default.version;
493
915
  var HELP_TEXT = `
494
916
  ${pc2.bold(pc2.cyan("@subramanyaks/env-drift"))} v${VERSION} \u2014 Detect environment variable drift and public secret leaks
495
917
 
@@ -497,17 +919,18 @@ ${pc2.bold("Usage:")}
497
919
  npx @subramanyaks/env-drift [options]
498
920
 
499
921
  ${pc2.bold("Options:")}
500
- -d, --dir <path> Project directory to scan (default: ".")
501
- --env <file> Local env file name (default: ".env")
502
- --example <file> Example env file name (default: ".env.example")
503
- --ignore <vars> Comma-separated env var names to ignore
504
- --sync Safely append missing keys to .env.example as KEY=
505
- --types Generate env.d.ts for detected env variables
506
- --types-out <path> Output path for --types (default: "env.d.ts")
507
- --ci Exit with code 1 if missing vars or secret leaks are found
508
- --json Output audit results as JSON
509
- -v, --version Show version
510
- -h, --help Show this help message
922
+ -d, --dir <path> Project directory to scan (default: ".")
923
+ --env <file> Local env file name (default: ".env")
924
+ --example <file> Example env file name (default: ".env.example")
925
+ --ignore <vars> Comma-separated env var names to ignore
926
+ --sync Safely append missing keys to .env.example as KEY=
927
+ --types Generate env.d.ts for detected env variables
928
+ --types-out <path> Output path for --types (default: "env.d.ts")
929
+ --ci Exit with code 1 if missing vars or secret leaks are found
930
+ --format <type> Output format: text, json, or github (default: "text")
931
+ --json Output audit results as JSON (alias for --format json)
932
+ -v, --version Show version
933
+ -h, --help Show this help message
511
934
  `;
512
935
  function runCli(argv = process.argv.slice(2)) {
513
936
  let values;
@@ -523,6 +946,7 @@ function runCli(argv = process.argv.slice(2)) {
523
946
  types: { type: "boolean", default: false },
524
947
  "types-out": { type: "string" },
525
948
  ci: { type: "boolean", default: false },
949
+ format: { type: "string" },
526
950
  json: { type: "boolean", default: false },
527
951
  version: { type: "boolean", short: "v", default: false },
528
952
  help: { type: "boolean", short: "h", default: false }
@@ -544,41 +968,75 @@ function runCli(argv = process.argv.slice(2)) {
544
968
  console.log(VERSION);
545
969
  return 0;
546
970
  }
547
- const rootDir = resolve2(typeof values.dir === "string" ? values.dir : process.cwd());
548
- const envFile = typeof values.env === "string" ? values.env : void 0;
549
- const exampleFile = typeof values.example === "string" ? values.example : ".env.example";
550
- const ignore = typeof values.ignore === "string" ? values.ignore.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
971
+ const format = values.json ? "json" : typeof values.format === "string" ? values.format.toLowerCase() : "text";
972
+ if (format !== "text" && format !== "json" && format !== "github") {
973
+ console.error(
974
+ pc2.red(`Error: Invalid --format "${format}". Expected "text", "json", or "github".`)
975
+ );
976
+ return 1;
977
+ }
978
+ const rootDir = resolve3(typeof values.dir === "string" ? values.dir : process.cwd());
979
+ let fileConfig;
980
+ try {
981
+ fileConfig = loadConfig(rootDir);
982
+ } catch (err) {
983
+ const msg = err instanceof Error ? err.message : String(err);
984
+ console.error(pc2.red(`Error: ${msg}`));
985
+ return 1;
986
+ }
987
+ const envFile = typeof values.env === "string" ? values.env : fileConfig.envFile;
988
+ const exampleFile = typeof values.example === "string" ? values.example : fileConfig.exampleFile ?? ".env.example";
989
+ const cliIgnore = typeof values.ignore === "string" ? values.ignore.split(",").map((s) => s.trim()).filter(Boolean) : [];
990
+ const mergedIgnore = [...fileConfig.ignore ?? [], ...cliIgnore];
551
991
  const result = auditEnv({
552
992
  rootDir,
553
993
  envFile,
554
994
  exampleFile,
555
- ignore
995
+ ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
996
+ ignoreDirs: fileConfig.ignoreDirs,
997
+ publicPrefixes: fileConfig.publicPrefixes,
998
+ sensitiveKeywords: fileConfig.sensitiveKeywords
556
999
  });
557
1000
  if (values.sync && result.missingInExample.length > 0) {
558
- const examplePath = resolve2(rootDir, exampleFile);
1001
+ const examplePath = resolve3(rootDir, exampleFile);
559
1002
  const synced = syncEnvExample(examplePath, result.missingInExample);
560
- if (!values.json && synced.added.length > 0) {
561
- const action = synced.created ? "Created" : "Updated";
562
- console.log(
563
- pc2.green(`\u2714 ${action} ${exampleFile} with ${synced.added.length} key(s): ${synced.added.join(", ")}`)
564
- );
1003
+ if (synced.added.length > 0) {
1004
+ const addedSet = new Set(synced.added);
1005
+ result.missingInExample = result.missingInExample.filter((k) => !addedSet.has(k));
1006
+ result.exampleFileExists = true;
1007
+ if (format === "text") {
1008
+ const action = synced.created ? "Created" : "Updated";
1009
+ console.log(
1010
+ pc2.green(`\u2714 ${action} ${exampleFile} with ${synced.added.length} key(s): ${synced.added.join(", ")}`)
1011
+ );
1012
+ }
565
1013
  }
566
1014
  }
567
1015
  if (values.types || typeof values["types-out"] === "string") {
568
1016
  const outFile = typeof values["types-out"] === "string" ? values["types-out"] : "env.d.ts";
569
- const outputPath = resolve2(rootDir, outFile);
1017
+ const outputPath = resolve3(rootDir, outFile);
570
1018
  const generated = writeEnvTypes(outputPath, result);
571
- if (!values.json) {
1019
+ if (format === "text") {
572
1020
  console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
573
1021
  }
574
1022
  }
575
- if (values.json) {
1023
+ if (format === "json") {
576
1024
  console.log(JSON.stringify(result, null, 2));
1025
+ } else if (format === "github") {
1026
+ const annotations = formatGitHubAnnotations(result, {
1027
+ envFile: envFile ?? ".env",
1028
+ exampleFile,
1029
+ ci: Boolean(values.ci)
1030
+ });
1031
+ if (annotations) {
1032
+ console.log(annotations);
1033
+ }
577
1034
  } else {
578
1035
  console.log(
579
1036
  formatAuditReport(result, {
580
1037
  envFile: envFile ?? ".env",
581
- exampleFile
1038
+ exampleFile,
1039
+ ci: Boolean(values.ci)
582
1040
  })
583
1041
  );
584
1042
  }
@@ -587,8 +1045,16 @@ function runCli(argv = process.argv.slice(2)) {
587
1045
  }
588
1046
  return 0;
589
1047
  }
590
- var isDirectExecution = process.argv[1] && (process.argv[1].endsWith("cli.js") || process.argv[1].endsWith("env-drift") || process.argv[1].endsWith("env-drift-cli"));
591
- if (isDirectExecution) {
1048
+ function isDirectExecution() {
1049
+ const entry = process.argv[1];
1050
+ if (!entry) return false;
1051
+ try {
1052
+ return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
1053
+ } catch {
1054
+ return entry.endsWith("cli.js") || entry.endsWith("env-drift") || entry.endsWith("env-drift-cli");
1055
+ }
1056
+ }
1057
+ if (isDirectExecution()) {
592
1058
  process.exitCode = runCli();
593
1059
  }
594
1060
  export {