@subramanyaks/env-drift 1.0.1 → 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
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { realpathSync } from "fs";
5
- import { resolve as resolve2 } from "path";
5
+ import { resolve as resolve3 } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import { parseArgs } from "util";
8
8
  import pc2 from "picocolors";
@@ -10,7 +10,7 @@ import pc2 from "picocolors";
10
10
  // package.json
11
11
  var package_default = {
12
12
  name: "@subramanyaks/env-drift",
13
- version: "1.0.1",
13
+ version: "1.1.0",
14
14
  description: "Zero-config CLI and library to detect environment variable drift, missing keys, dead vars, and accidental public secret exposure.",
15
15
  type: "module",
16
16
  publishConfig: {
@@ -32,6 +32,7 @@ var package_default = {
32
32
  files: [
33
33
  "dist",
34
34
  "README.md",
35
+ "CHANGELOG.md",
35
36
  "LICENSE"
36
37
  ],
37
38
  engines: {
@@ -125,8 +126,10 @@ function parseEnvContent(content) {
125
126
  const seen = /* @__PURE__ */ new Set();
126
127
  const duplicateSet = /* @__PURE__ */ new Set();
127
128
  const values = {};
129
+ const keyLines = {};
128
130
  const lines = content.split(/\r?\n/);
129
- for (const rawLine of lines) {
131
+ for (let i = 0; i < lines.length; i++) {
132
+ const rawLine = lines[i];
130
133
  const line = rawLine.trim();
131
134
  if (!line || line.startsWith("#")) continue;
132
135
  const match = ENV_LINE_REGEX.exec(line);
@@ -141,10 +144,12 @@ function parseEnvContent(content) {
141
144
  keys.push(key);
142
145
  }
143
146
  values[key] = parseValue(rawValue);
147
+ keyLines[key] = i + 1;
144
148
  }
145
149
  return {
146
150
  keys,
147
151
  values,
152
+ lines: keyLines,
148
153
  duplicates: Array.from(duplicateSet)
149
154
  };
150
155
  }
@@ -155,16 +160,18 @@ function parseEnvFile(filePath) {
155
160
  exists: false,
156
161
  keys: [],
157
162
  values: {},
163
+ lines: {},
158
164
  duplicates: []
159
165
  };
160
166
  }
161
167
  const content = readFileSync(filePath, "utf-8");
162
- const { keys, values, duplicates } = parseEnvContent(content);
168
+ const { keys, values, lines, duplicates } = parseEnvContent(content);
163
169
  return {
164
170
  filePath,
165
171
  exists: true,
166
172
  keys,
167
173
  values,
174
+ lines,
168
175
  duplicates
169
176
  };
170
177
  }
@@ -236,35 +243,48 @@ function getLineNumber(source, index) {
236
243
  }
237
244
  return line;
238
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
+ }
239
259
  function extractEnvReferences(content, filePath) {
260
+ const ignoredLines = collectIgnoredLines(content);
240
261
  const cleaned = stripCommentsPreservingLines(content);
241
262
  const refs = [];
242
263
  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;
264
+ const addRef = (name, line, source) => {
265
+ if (ignoredLines.has(line)) return;
248
266
  refs.push({
249
267
  name,
250
268
  file: normalizedFile,
251
- line: getLineNumber(cleaned, match.index),
269
+ line,
252
270
  source
253
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);
254
279
  }
255
- const bracketRegex = /\b(process\.env|import\.meta\.env)\s*(?:\?\.)?\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;
256
281
  for (const match of cleaned.matchAll(bracketRegex)) {
257
282
  const source = match[1];
258
283
  const name = match[2];
259
284
  if (!name || match.index === void 0) continue;
260
- refs.push({
261
- name,
262
- file: normalizedFile,
263
- line: getLineNumber(cleaned, match.index),
264
- source
265
- });
285
+ addRef(name, getLineNumber(cleaned, match.index), source);
266
286
  }
267
- 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;
268
288
  for (const match of cleaned.matchAll(destructureRegex)) {
269
289
  const body = match[1];
270
290
  const source = match[2];
@@ -281,14 +301,15 @@ function extractEnvReferences(content, filePath) {
281
301
  if (!name) continue;
282
302
  const leadingWs = part.indexOf(name);
283
303
  const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
284
- refs.push({
285
- name,
286
- file: normalizedFile,
287
- line: getLineNumber(cleaned, absoluteIdx),
288
- source
289
- });
304
+ addRef(name, getLineNumber(cleaned, absoluteIdx), source);
290
305
  }
291
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
+ }
292
313
  refs.sort((a, b) => a.line - b.line);
293
314
  return refs;
294
315
  }
@@ -356,12 +377,87 @@ var SENSITIVE_KEYWORDS = [
356
377
  "SERVICE_ROLE",
357
378
  "CREDENTIALS"
358
379
  ];
359
- 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) {
360
454
  const upper = name.toUpperCase();
361
- 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));
362
458
  if (!prefix) return null;
363
459
  const rest = upper.slice(prefix.length);
364
- const matchedKeyword = SENSITIVE_KEYWORDS.find((kw) => rest.includes(kw));
460
+ const matchedKeyword = keywords.find((kw) => rest.includes(kw));
365
461
  if (!matchedKeyword) return null;
366
462
  return { prefix, matchedKeyword };
367
463
  }
@@ -370,7 +466,8 @@ function auditEnv(options = {}) {
370
466
  const envFileName = options.envFile ?? ".env";
371
467
  const exampleFileName = options.exampleFile ?? ".env.example";
372
468
  const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
373
- 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 });
374
471
  const usedInCode = {};
375
472
  for (const ref of references) {
376
473
  if (!usedInCode[ref.name]) {
@@ -382,6 +479,7 @@ function auditEnv(options = {}) {
382
479
  const parsedExample = parseEnvFile(resolve(rootDir, exampleFileName));
383
480
  let envFileExists = parsedEnv.exists;
384
481
  const localEnvKeys = new Set(parsedEnv.keys);
482
+ const localEnvValues = { ...parsedEnv.values };
385
483
  if (!options.envFile) {
386
484
  const parsedLocal = parseEnvFile(resolve(rootDir, ".env.local"));
387
485
  if (parsedLocal.exists) {
@@ -389,6 +487,7 @@ function auditEnv(options = {}) {
389
487
  }
390
488
  for (const key of parsedLocal.keys) {
391
489
  localEnvKeys.add(key);
490
+ localEnvValues[key] = parsedLocal.values[key] ?? "";
392
491
  }
393
492
  }
394
493
  const exampleKeys = new Set(parsedExample.keys);
@@ -396,6 +495,9 @@ function auditEnv(options = {}) {
396
495
  const codeKeySet = new Set(codeKeys);
397
496
  const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
398
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();
399
501
  const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
400
502
  const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
401
503
  const allKnownKeys = /* @__PURE__ */ new Set([
@@ -406,7 +508,10 @@ function auditEnv(options = {}) {
406
508
  const secretExposures = [];
407
509
  for (const key of Array.from(allKnownKeys).sort()) {
408
510
  if (ignoreSet.has(key)) continue;
409
- const hit = detectSecretExposure(key);
511
+ const hit = detectSecretExposure(key, {
512
+ publicPrefixes: options.publicPrefixes,
513
+ sensitiveKeywords: options.sensitiveKeywords
514
+ });
410
515
  if (hit) {
411
516
  secretExposures.push({
412
517
  name: key,
@@ -416,6 +521,19 @@ function auditEnv(options = {}) {
416
521
  });
417
522
  }
418
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
+ }
419
537
  return {
420
538
  rootDir,
421
539
  scannedFiles,
@@ -424,9 +542,11 @@ function auditEnv(options = {}) {
424
542
  usedInCode,
425
543
  missingInEnv,
426
544
  missingInExample,
545
+ emptyInEnv,
427
546
  unusedInEnv,
428
547
  unusedInExample,
429
548
  secretExposures,
549
+ exampleSecretLeaks,
430
550
  duplicateKeys: {
431
551
  env: parsedEnv.duplicates,
432
552
  example: parsedExample.duplicates
@@ -434,6 +554,57 @@ function auditEnv(options = {}) {
434
554
  };
435
555
  }
436
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
+
437
608
  // src/reporter.ts
438
609
  import pc from "picocolors";
439
610
  function formatRefs(refs) {
@@ -444,7 +615,7 @@ function formatRefs(refs) {
444
615
  }
445
616
  function hasBlockingIssues(result, options = {}) {
446
617
  const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
447
- return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0;
618
+ return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
448
619
  }
449
620
  function formatAuditReport(result, options = {}) {
450
621
  const envFile = options.envFile ?? ".env";
@@ -458,7 +629,7 @@ function formatAuditReport(result, options = {}) {
458
629
  )}`
459
630
  );
460
631
  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;
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;
462
633
  if (totalIssues === 0) {
463
634
  lines.push(pc.green("\u2714 No environment drift detected. Everything is in sync!"));
464
635
  if (skipMissingInEnv && result.missingInEnv.length > 0) {
@@ -480,6 +651,19 @@ function formatAuditReport(result, options = {}) {
480
651
  }
481
652
  lines.push("");
482
653
  }
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
+ }
483
667
  if (!skipMissingInEnv && result.missingInEnv.length > 0) {
484
668
  lines.push(pc.bold(pc.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
485
669
  for (const key of result.missingInEnv) {
@@ -499,6 +683,13 @@ function formatAuditReport(result, options = {}) {
499
683
  }
500
684
  lines.push("");
501
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
+ }
502
693
  if (result.unusedInEnv.length > 0) {
503
694
  lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
504
695
  for (const key of result.unusedInEnv) {
@@ -531,6 +722,127 @@ function formatAuditReport(result, options = {}) {
531
722
  }
532
723
  return lines.join("\n");
533
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
+ }
534
846
 
535
847
  // src/typegen.ts
536
848
  import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
@@ -607,17 +919,18 @@ ${pc2.bold("Usage:")}
607
919
  npx @subramanyaks/env-drift [options]
608
920
 
609
921
  ${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
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
621
934
  `;
622
935
  function runCli(argv = process.argv.slice(2)) {
623
936
  let values;
@@ -633,6 +946,7 @@ function runCli(argv = process.argv.slice(2)) {
633
946
  types: { type: "boolean", default: false },
634
947
  "types-out": { type: "string" },
635
948
  ci: { type: "boolean", default: false },
949
+ format: { type: "string" },
636
950
  json: { type: "boolean", default: false },
637
951
  version: { type: "boolean", short: "v", default: false },
638
952
  help: { type: "boolean", short: "h", default: false }
@@ -654,24 +968,43 @@ function runCli(argv = process.argv.slice(2)) {
654
968
  console.log(VERSION);
655
969
  return 0;
656
970
  }
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;
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];
661
991
  const result = auditEnv({
662
992
  rootDir,
663
993
  envFile,
664
994
  exampleFile,
665
- ignore
995
+ ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
996
+ ignoreDirs: fileConfig.ignoreDirs,
997
+ publicPrefixes: fileConfig.publicPrefixes,
998
+ sensitiveKeywords: fileConfig.sensitiveKeywords
666
999
  });
667
1000
  if (values.sync && result.missingInExample.length > 0) {
668
- const examplePath = resolve2(rootDir, exampleFile);
1001
+ const examplePath = resolve3(rootDir, exampleFile);
669
1002
  const synced = syncEnvExample(examplePath, result.missingInExample);
670
1003
  if (synced.added.length > 0) {
671
1004
  const addedSet = new Set(synced.added);
672
1005
  result.missingInExample = result.missingInExample.filter((k) => !addedSet.has(k));
673
1006
  result.exampleFileExists = true;
674
- if (!values.json) {
1007
+ if (format === "text") {
675
1008
  const action = synced.created ? "Created" : "Updated";
676
1009
  console.log(
677
1010
  pc2.green(`\u2714 ${action} ${exampleFile} with ${synced.added.length} key(s): ${synced.added.join(", ")}`)
@@ -681,14 +1014,23 @@ function runCli(argv = process.argv.slice(2)) {
681
1014
  }
682
1015
  if (values.types || typeof values["types-out"] === "string") {
683
1016
  const outFile = typeof values["types-out"] === "string" ? values["types-out"] : "env.d.ts";
684
- const outputPath = resolve2(rootDir, outFile);
1017
+ const outputPath = resolve3(rootDir, outFile);
685
1018
  const generated = writeEnvTypes(outputPath, result);
686
- if (!values.json) {
1019
+ if (format === "text") {
687
1020
  console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
688
1021
  }
689
1022
  }
690
- if (values.json) {
1023
+ if (format === "json") {
691
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
+ }
692
1034
  } else {
693
1035
  console.log(
694
1036
  formatAuditReport(result, {