@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/index.js CHANGED
@@ -8,8 +8,27 @@ function parseValue(raw) {
8
8
  const trimmed = raw.trim();
9
9
  if (!trimmed) return "";
10
10
  const quote = trimmed[0];
11
- if (quote === '"' || quote === "'") {
12
- const closingIdx = trimmed.indexOf(quote, 1);
11
+ if (quote === '"') {
12
+ let result = "";
13
+ for (let i = 1; i < trimmed.length; i++) {
14
+ const ch = trimmed[i];
15
+ if (ch === "\\" && i + 1 < trimmed.length) {
16
+ const next = trimmed[i + 1];
17
+ if (next === "n") result += "\n";
18
+ else if (next === "r") result += "\r";
19
+ else if (next === "t") result += " ";
20
+ else result += next;
21
+ i++;
22
+ } else if (ch === '"') {
23
+ return result;
24
+ } else {
25
+ result += ch;
26
+ }
27
+ }
28
+ return result;
29
+ }
30
+ if (quote === "'") {
31
+ const closingIdx = trimmed.indexOf("'", 1);
13
32
  if (closingIdx !== -1) {
14
33
  return trimmed.slice(1, closingIdx);
15
34
  }
@@ -26,8 +45,10 @@ function parseEnvContent(content) {
26
45
  const seen = /* @__PURE__ */ new Set();
27
46
  const duplicateSet = /* @__PURE__ */ new Set();
28
47
  const values = {};
48
+ const keyLines = {};
29
49
  const lines = content.split(/\r?\n/);
30
- for (const rawLine of lines) {
50
+ for (let i = 0; i < lines.length; i++) {
51
+ const rawLine = lines[i];
31
52
  const line = rawLine.trim();
32
53
  if (!line || line.startsWith("#")) continue;
33
54
  const match = ENV_LINE_REGEX.exec(line);
@@ -42,10 +63,12 @@ function parseEnvContent(content) {
42
63
  keys.push(key);
43
64
  }
44
65
  values[key] = parseValue(rawValue);
66
+ keyLines[key] = i + 1;
45
67
  }
46
68
  return {
47
69
  keys,
48
70
  values,
71
+ lines: keyLines,
49
72
  duplicates: Array.from(duplicateSet)
50
73
  };
51
74
  }
@@ -56,16 +79,18 @@ function parseEnvFile(filePath) {
56
79
  exists: false,
57
80
  keys: [],
58
81
  values: {},
82
+ lines: {},
59
83
  duplicates: []
60
84
  };
61
85
  }
62
86
  const content = readFileSync(filePath, "utf-8");
63
- const { keys, values, duplicates } = parseEnvContent(content);
87
+ const { keys, values, lines, duplicates } = parseEnvContent(content);
64
88
  return {
65
89
  filePath,
66
90
  exists: true,
67
91
  keys,
68
92
  values,
93
+ lines,
69
94
  duplicates
70
95
  };
71
96
  }
@@ -137,35 +162,48 @@ function getLineNumber(source, index) {
137
162
  }
138
163
  return line;
139
164
  }
165
+ function collectIgnoredLines(source) {
166
+ const ignored = /* @__PURE__ */ new Set();
167
+ const lines = source.split(/\r?\n/);
168
+ for (let i = 0; i < lines.length; i++) {
169
+ const line = lines[i];
170
+ if (/(?:\/\/|\/\*)\s*env-drift-ignore-next-line\b/.test(line)) {
171
+ ignored.add(i + 2);
172
+ } else if (/(?:\/\/|\/\*)\s*env-drift-ignore\b/.test(line)) {
173
+ ignored.add(i + 1);
174
+ }
175
+ }
176
+ return ignored;
177
+ }
140
178
  function extractEnvReferences(content, filePath) {
179
+ const ignoredLines = collectIgnoredLines(content);
141
180
  const cleaned = stripCommentsPreservingLines(content);
142
181
  const refs = [];
143
182
  const normalizedFile = filePath.replace(/\\/g, "/");
144
- const dotRegex = /\b(process\.env|import\.meta\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
145
- for (const match of cleaned.matchAll(dotRegex)) {
146
- const source = match[1];
147
- const name = match[2];
148
- if (!name || match.index === void 0) continue;
183
+ const addRef = (name, line, source) => {
184
+ if (ignoredLines.has(line)) return;
149
185
  refs.push({
150
186
  name,
151
187
  file: normalizedFile,
152
- line: getLineNumber(cleaned, match.index),
188
+ line,
153
189
  source
154
190
  });
191
+ };
192
+ const dotRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
193
+ for (const match of cleaned.matchAll(dotRegex)) {
194
+ const source = match[1];
195
+ const name = match[2];
196
+ if (!name || match.index === void 0) continue;
197
+ addRef(name, getLineNumber(cleaned, match.index), source);
155
198
  }
156
- const bracketRegex = /\b(process\.env|import\.meta\.env)\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
199
+ const bracketRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
157
200
  for (const match of cleaned.matchAll(bracketRegex)) {
158
201
  const source = match[1];
159
202
  const name = match[2];
160
203
  if (!name || match.index === void 0) continue;
161
- refs.push({
162
- name,
163
- file: normalizedFile,
164
- line: getLineNumber(cleaned, match.index),
165
- source
166
- });
204
+ addRef(name, getLineNumber(cleaned, match.index), source);
167
205
  }
168
- const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
206
+ const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env|Bun\.env)\b/g;
169
207
  for (const match of cleaned.matchAll(destructureRegex)) {
170
208
  const body = match[1];
171
209
  const source = match[2];
@@ -182,14 +220,15 @@ function extractEnvReferences(content, filePath) {
182
220
  if (!name) continue;
183
221
  const leadingWs = part.indexOf(name);
184
222
  const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
185
- refs.push({
186
- name,
187
- file: normalizedFile,
188
- line: getLineNumber(cleaned, absoluteIdx),
189
- source
190
- });
223
+ addRef(name, getLineNumber(cleaned, absoluteIdx), source);
191
224
  }
192
225
  }
226
+ const denoRegex = /\bDeno\.env\s*\??\.\s*get\s*\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\)/g;
227
+ for (const match of cleaned.matchAll(denoRegex)) {
228
+ const name = match[1];
229
+ if (!name || match.index === void 0) continue;
230
+ addRef(name, getLineNumber(cleaned, match.index), "Deno.env");
231
+ }
193
232
  refs.sort((a, b) => a.line - b.line);
194
233
  return refs;
195
234
  }
@@ -257,12 +296,87 @@ var SENSITIVE_KEYWORDS = [
257
296
  "SERVICE_ROLE",
258
297
  "CREDENTIALS"
259
298
  ];
260
- function detectSecretExposure(name) {
299
+ var PLACEHOLDER_VALUE_PATTERNS = [
300
+ /^your[_-]/i,
301
+ /^my[_-]/i,
302
+ /^change[_-]?me$/i,
303
+ /^replace[_-]?me$/i,
304
+ /^placeholder$/i,
305
+ /^example$/i,
306
+ /^dummy$/i,
307
+ /^test$/i,
308
+ /^todo$/i,
309
+ /^<[^>]+>$/,
310
+ /^\$\{[^}]+\}$/,
311
+ /^[xX*]{4,}$/
312
+ ];
313
+ var PLACEHOLDER_URL_PASSWORDS = /* @__PURE__ */ new Set([
314
+ "password",
315
+ "pass",
316
+ "passwd",
317
+ "postgres",
318
+ "root",
319
+ "admin",
320
+ "changeme",
321
+ "change_me",
322
+ "secret",
323
+ "example",
324
+ "dummy",
325
+ "test",
326
+ "1234",
327
+ "123456",
328
+ "your_password",
329
+ "<password>"
330
+ ]);
331
+ var EXAMPLE_SECRET_PATTERNS = [
332
+ { pattern: /^sk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe live secret key" },
333
+ { pattern: /^rk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe restricted live key" },
334
+ { pattern: /^whsec_[A-Za-z0-9]{16,}$/, reason: "Stripe webhook secret" },
335
+ { pattern: /^gh[pous]_[A-Za-z0-9]{20,}$/, reason: "GitHub access token" },
336
+ { pattern: /^github_pat_[A-Za-z0-9_]{20,}$/, reason: "GitHub fine-grained token" },
337
+ { pattern: /^AKIA[0-9A-Z]{16}$/, reason: "AWS Access Key ID" },
338
+ { pattern: /^sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}$/, reason: "AI provider API key" },
339
+ { pattern: /^sk-[A-Za-z0-9]{32,}$/, reason: "Secret API key (sk-...)" },
340
+ { pattern: /^xox[baprs]-[A-Za-z0-9-]{10,}$/, reason: "Slack token" },
341
+ { pattern: /^AIza[0-9A-Za-z_-]{35}$/, reason: "Google API key" },
342
+ {
343
+ pattern: /^eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}$/,
344
+ reason: "JWT token"
345
+ },
346
+ {
347
+ pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
348
+ reason: "PEM private key"
349
+ }
350
+ ];
351
+ var CONNECTION_URL_PASSWORD_REGEX = /^(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^:\s/]+:([^@\s/]+)@/i;
352
+ function detectExampleSecretLeak(_name, value) {
353
+ const trimmed = value.trim();
354
+ if (!trimmed) return null;
355
+ if (PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(trimmed))) {
356
+ return null;
357
+ }
358
+ for (const { pattern, reason } of EXAMPLE_SECRET_PATTERNS) {
359
+ if (pattern.test(trimmed)) {
360
+ return reason;
361
+ }
362
+ }
363
+ const urlMatch = CONNECTION_URL_PASSWORD_REGEX.exec(trimmed);
364
+ if (urlMatch) {
365
+ const password = urlMatch[1] ?? "";
366
+ if (password && !PLACEHOLDER_URL_PASSWORDS.has(password.toLowerCase()) && !PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(password))) {
367
+ return "Connection URL with embedded password";
368
+ }
369
+ }
370
+ return null;
371
+ }
372
+ function detectSecretExposure(name, options) {
261
373
  const upper = name.toUpperCase();
262
- const prefix = PUBLIC_ENV_PREFIXES.find((p) => upper.startsWith(p));
374
+ const prefixes = options?.publicPrefixes?.length ? [...PUBLIC_ENV_PREFIXES, ...options.publicPrefixes.map((p) => p.toUpperCase())] : PUBLIC_ENV_PREFIXES;
375
+ const keywords = options?.sensitiveKeywords?.length ? [...SENSITIVE_KEYWORDS, ...options.sensitiveKeywords.map((k) => k.toUpperCase())] : SENSITIVE_KEYWORDS;
376
+ const prefix = prefixes.find((p) => upper.startsWith(p));
263
377
  if (!prefix) return null;
264
378
  const rest = upper.slice(prefix.length);
265
- const matchedKeyword = SENSITIVE_KEYWORDS.find((kw) => rest.includes(kw));
379
+ const matchedKeyword = keywords.find((kw) => rest.includes(kw));
266
380
  if (!matchedKeyword) return null;
267
381
  return { prefix, matchedKeyword };
268
382
  }
@@ -271,7 +385,8 @@ function auditEnv(options = {}) {
271
385
  const envFileName = options.envFile ?? ".env";
272
386
  const exampleFileName = options.exampleFile ?? ".env.example";
273
387
  const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
274
- const { scannedFiles, references } = scanFiles(rootDir);
388
+ const ignoreDirs = options.ignoreDirs?.length ? [...DEFAULT_IGNORE_DIRS, ...options.ignoreDirs] : void 0;
389
+ const { scannedFiles, references } = scanFiles(rootDir, { ignoreDirs });
275
390
  const usedInCode = {};
276
391
  for (const ref of references) {
277
392
  if (!usedInCode[ref.name]) {
@@ -281,11 +396,17 @@ function auditEnv(options = {}) {
281
396
  }
282
397
  const parsedEnv = parseEnvFile(resolve(rootDir, envFileName));
283
398
  const parsedExample = parseEnvFile(resolve(rootDir, exampleFileName));
399
+ let envFileExists = parsedEnv.exists;
284
400
  const localEnvKeys = new Set(parsedEnv.keys);
401
+ const localEnvValues = { ...parsedEnv.values };
285
402
  if (!options.envFile) {
286
403
  const parsedLocal = parseEnvFile(resolve(rootDir, ".env.local"));
404
+ if (parsedLocal.exists) {
405
+ envFileExists = true;
406
+ }
287
407
  for (const key of parsedLocal.keys) {
288
408
  localEnvKeys.add(key);
409
+ localEnvValues[key] = parsedLocal.values[key] ?? "";
289
410
  }
290
411
  }
291
412
  const exampleKeys = new Set(parsedExample.keys);
@@ -293,6 +414,9 @@ function auditEnv(options = {}) {
293
414
  const codeKeySet = new Set(codeKeys);
294
415
  const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
295
416
  const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
417
+ const emptyInEnv = codeKeys.filter(
418
+ (k) => !ignoreSet.has(k) && localEnvKeys.has(k) && (localEnvValues[k] ?? "").trim() === ""
419
+ ).sort();
296
420
  const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
297
421
  const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
298
422
  const allKnownKeys = /* @__PURE__ */ new Set([
@@ -303,7 +427,10 @@ function auditEnv(options = {}) {
303
427
  const secretExposures = [];
304
428
  for (const key of Array.from(allKnownKeys).sort()) {
305
429
  if (ignoreSet.has(key)) continue;
306
- const hit = detectSecretExposure(key);
430
+ const hit = detectSecretExposure(key, {
431
+ publicPrefixes: options.publicPrefixes,
432
+ sensitiveKeywords: options.sensitiveKeywords
433
+ });
307
434
  if (hit) {
308
435
  secretExposures.push({
309
436
  name: key,
@@ -313,15 +440,32 @@ function auditEnv(options = {}) {
313
440
  });
314
441
  }
315
442
  }
443
+ const exampleSecretLeaks = [];
444
+ for (const key of [...parsedExample.keys].sort()) {
445
+ if (ignoreSet.has(key)) continue;
446
+ const reason = detectExampleSecretLeak(key, parsedExample.values[key] ?? "");
447
+ if (reason) {
448
+ exampleSecretLeaks.push({
449
+ name: key,
450
+ reason,
451
+ file: exampleFileName,
452
+ line: parsedExample.lines[key] ?? 1
453
+ });
454
+ }
455
+ }
316
456
  return {
317
457
  rootDir,
318
458
  scannedFiles,
459
+ envFileExists,
460
+ exampleFileExists: parsedExample.exists,
319
461
  usedInCode,
320
462
  missingInEnv,
321
463
  missingInExample,
464
+ emptyInEnv,
322
465
  unusedInEnv,
323
466
  unusedInExample,
324
467
  secretExposures,
468
+ exampleSecretLeaks,
325
469
  duplicateKeys: {
326
470
  env: parsedEnv.duplicates,
327
471
  example: parsedExample.duplicates
@@ -329,6 +473,57 @@ function auditEnv(options = {}) {
329
473
  };
330
474
  }
331
475
 
476
+ // src/config.ts
477
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
478
+ import { resolve as resolve2 } from "path";
479
+ function toStringArray(val) {
480
+ if (!Array.isArray(val)) return void 0;
481
+ return val.filter((item) => typeof item === "string" && item.trim().length > 0);
482
+ }
483
+ function normalizeConfig(raw) {
484
+ if (!raw || typeof raw !== "object") return {};
485
+ const obj = raw;
486
+ const config = {};
487
+ if (typeof obj.envFile === "string" && obj.envFile.trim()) {
488
+ config.envFile = obj.envFile.trim();
489
+ }
490
+ if (typeof obj.exampleFile === "string" && obj.exampleFile.trim()) {
491
+ config.exampleFile = obj.exampleFile.trim();
492
+ }
493
+ const ignore = toStringArray(obj.ignore);
494
+ if (ignore) config.ignore = ignore;
495
+ const ignoreDirs = toStringArray(obj.ignoreDirs);
496
+ if (ignoreDirs) config.ignoreDirs = ignoreDirs;
497
+ const publicPrefixes = toStringArray(obj.publicPrefixes);
498
+ if (publicPrefixes) config.publicPrefixes = publicPrefixes;
499
+ const sensitiveKeywords = toStringArray(obj.sensitiveKeywords);
500
+ if (sensitiveKeywords) config.sensitiveKeywords = sensitiveKeywords;
501
+ return config;
502
+ }
503
+ function loadConfig(rootDir) {
504
+ const rcPath = resolve2(rootDir, ".envdriftrc.json");
505
+ if (existsSync2(rcPath)) {
506
+ try {
507
+ const parsed = JSON.parse(readFileSync3(rcPath, "utf-8"));
508
+ return normalizeConfig(parsed);
509
+ } catch (err) {
510
+ const msg = err instanceof Error ? err.message : String(err);
511
+ throw new Error(`Failed to parse .envdriftrc.json: ${msg}`);
512
+ }
513
+ }
514
+ const pkgPath = resolve2(rootDir, "package.json");
515
+ if (existsSync2(pkgPath)) {
516
+ try {
517
+ const parsed = JSON.parse(readFileSync3(pkgPath, "utf-8"));
518
+ if (parsed && typeof parsed === "object" && parsed["env-drift"]) {
519
+ return normalizeConfig(parsed["env-drift"]);
520
+ }
521
+ } catch {
522
+ }
523
+ }
524
+ return {};
525
+ }
526
+
332
527
  // src/typegen.ts
333
528
  import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
334
529
  import { dirname } from "path";
@@ -403,12 +598,14 @@ function formatRefs(refs) {
403
598
  const extra = refs.length > 2 ? ` (+${refs.length - 2} more)` : "";
404
599
  return pc.dim(` \u2190 ${shown.join(", ")}${extra}`);
405
600
  }
406
- function hasBlockingIssues(result) {
407
- return result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0;
601
+ function hasBlockingIssues(result, options = {}) {
602
+ const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
603
+ return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
408
604
  }
409
605
  function formatAuditReport(result, options = {}) {
410
606
  const envFile = options.envFile ?? ".env";
411
607
  const exampleFile = options.exampleFile ?? ".env.example";
608
+ const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
412
609
  const lines = [];
413
610
  lines.push("");
414
611
  lines.push(
@@ -417,9 +614,14 @@ function formatAuditReport(result, options = {}) {
417
614
  )}`
418
615
  );
419
616
  lines.push("");
420
- 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;
617
+ 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;
421
618
  if (totalIssues === 0) {
422
619
  lines.push(pc.green("\u2714 No environment drift detected. Everything is in sync!"));
620
+ if (skipMissingInEnv && result.missingInEnv.length > 0) {
621
+ lines.push(
622
+ pc.dim(` (No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode)`)
623
+ );
624
+ }
423
625
  lines.push("");
424
626
  return lines.join("\n");
425
627
  }
@@ -434,12 +636,30 @@ function formatAuditReport(result, options = {}) {
434
636
  }
435
637
  lines.push("");
436
638
  }
437
- if (result.missingInEnv.length > 0) {
639
+ if (result.exampleSecretLeaks.length > 0) {
640
+ lines.push(
641
+ pc.bold(pc.red(`\u2716 Possible Real Secret in ${exampleFile} (${result.exampleSecretLeaks.length})`))
642
+ );
643
+ for (const item of result.exampleSecretLeaks) {
644
+ lines.push(
645
+ ` ${pc.red("\u2022")} ${pc.bold(item.name)} ${pc.dim(
646
+ `(${item.reason}) \u2190 ${item.file}:${item.line}`
647
+ )}`
648
+ );
649
+ }
650
+ lines.push("");
651
+ }
652
+ if (!skipMissingInEnv && result.missingInEnv.length > 0) {
438
653
  lines.push(pc.bold(pc.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
439
654
  for (const key of result.missingInEnv) {
440
655
  lines.push(` ${pc.red("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
441
656
  }
442
657
  lines.push("");
658
+ } else if (skipMissingInEnv && result.missingInEnv.length > 0) {
659
+ lines.push(
660
+ pc.dim(`\u2139 No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode`)
661
+ );
662
+ lines.push("");
443
663
  }
444
664
  if (result.missingInExample.length > 0) {
445
665
  lines.push(pc.bold(pc.yellow(`\u26A0 Missing in ${exampleFile} (${result.missingInExample.length})`)));
@@ -448,6 +668,13 @@ function formatAuditReport(result, options = {}) {
448
668
  }
449
669
  lines.push("");
450
670
  }
671
+ if (result.emptyInEnv.length > 0) {
672
+ lines.push(pc.bold(pc.yellow(`\u26A0 Empty Value in ${envFile} (${result.emptyInEnv.length})`)));
673
+ for (const key of result.emptyInEnv) {
674
+ lines.push(` ${pc.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
675
+ }
676
+ lines.push("");
677
+ }
451
678
  if (result.unusedInEnv.length > 0) {
452
679
  lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
453
680
  for (const key of result.unusedInEnv) {
@@ -480,6 +707,127 @@ function formatAuditReport(result, options = {}) {
480
707
  }
481
708
  return lines.join("\n");
482
709
  }
710
+ function escapeGitHubData(value) {
711
+ return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
712
+ }
713
+ function escapeGitHubProperty(value) {
714
+ return escapeGitHubData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
715
+ }
716
+ function buildAnnotation(level, title, message, file, line) {
717
+ const props = [];
718
+ if (file) props.push(`file=${escapeGitHubProperty(file)}`);
719
+ if (line !== void 0) props.push(`line=${line}`);
720
+ props.push(`title=${escapeGitHubProperty(title)}`);
721
+ return `::${level} ${props.join(",")}::${escapeGitHubData(message)}`;
722
+ }
723
+ function formatGitHubAnnotations(result, options = {}) {
724
+ const envFile = options.envFile ?? ".env";
725
+ const exampleFile = options.exampleFile ?? ".env.example";
726
+ const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
727
+ const lines = [];
728
+ for (const item of result.secretExposures) {
729
+ const firstRef = item.references[0];
730
+ lines.push(
731
+ buildAnnotation(
732
+ "error",
733
+ "Public Secret Exposure",
734
+ `${item.name} uses client-exposed prefix "${item.prefix}" with sensitive keyword "${item.matchedKeyword}"`,
735
+ firstRef?.file,
736
+ firstRef?.line
737
+ )
738
+ );
739
+ }
740
+ for (const leak of result.exampleSecretLeaks) {
741
+ lines.push(
742
+ buildAnnotation(
743
+ "error",
744
+ `Secret Leak in ${exampleFile}`,
745
+ `${leak.name} appears to contain a real secret (${leak.reason}). Replace it with an empty placeholder.`,
746
+ leak.file,
747
+ leak.line
748
+ )
749
+ );
750
+ }
751
+ if (!skipMissingInEnv) {
752
+ for (const key of result.missingInEnv) {
753
+ const firstRef = result.usedInCode[key]?.[0];
754
+ lines.push(
755
+ buildAnnotation(
756
+ "error",
757
+ `Missing in ${envFile}`,
758
+ `Environment variable ${key} is referenced in code but missing in ${envFile}`,
759
+ firstRef?.file,
760
+ firstRef?.line
761
+ )
762
+ );
763
+ }
764
+ }
765
+ for (const key of result.missingInExample) {
766
+ const firstRef = result.usedInCode[key]?.[0];
767
+ lines.push(
768
+ buildAnnotation(
769
+ "error",
770
+ `Missing in ${exampleFile}`,
771
+ `Environment variable ${key} is referenced in code but missing in ${exampleFile}. Run \`env-drift --sync\` to update.`,
772
+ firstRef?.file,
773
+ firstRef?.line
774
+ )
775
+ );
776
+ }
777
+ for (const key of result.emptyInEnv) {
778
+ const firstRef = result.usedInCode[key]?.[0];
779
+ lines.push(
780
+ buildAnnotation(
781
+ "warning",
782
+ `Empty Value in ${envFile}`,
783
+ `Environment variable ${key} is defined in ${envFile} with an empty value`,
784
+ firstRef?.file,
785
+ firstRef?.line
786
+ )
787
+ );
788
+ }
789
+ for (const key of result.unusedInEnv) {
790
+ lines.push(
791
+ buildAnnotation(
792
+ "warning",
793
+ `Unused in ${envFile}`,
794
+ `Environment variable ${key} is defined in ${envFile} but not referenced in code`,
795
+ envFile
796
+ )
797
+ );
798
+ }
799
+ for (const key of result.unusedInExample) {
800
+ lines.push(
801
+ buildAnnotation(
802
+ "warning",
803
+ `Unused in ${exampleFile}`,
804
+ `Environment variable ${key} is defined in ${exampleFile} but not referenced in code`,
805
+ exampleFile
806
+ )
807
+ );
808
+ }
809
+ for (const key of result.duplicateKeys.env) {
810
+ lines.push(
811
+ buildAnnotation(
812
+ "warning",
813
+ `Duplicate Key in ${envFile}`,
814
+ `Environment variable ${key} is defined multiple times in ${envFile}`,
815
+ envFile
816
+ )
817
+ );
818
+ }
819
+ for (const key of result.duplicateKeys.example) {
820
+ lines.push(
821
+ buildAnnotation(
822
+ "warning",
823
+ `Duplicate Key in ${exampleFile}`,
824
+ `Environment variable ${key} is defined multiple times in ${exampleFile}`,
825
+ exampleFile
826
+ )
827
+ );
828
+ }
829
+ return lines.join("\n");
830
+ }
483
831
  export {
484
832
  BUILTIN_ENV_VARS,
485
833
  DEFAULT_EXTENSIONS,
@@ -487,11 +835,14 @@ export {
487
835
  PUBLIC_ENV_PREFIXES,
488
836
  SENSITIVE_KEYWORDS,
489
837
  auditEnv,
838
+ detectExampleSecretLeak,
490
839
  detectSecretExposure,
491
840
  extractEnvReferences,
492
841
  formatAuditReport,
842
+ formatGitHubAnnotations,
493
843
  generateEnvTypes,
494
844
  hasBlockingIssues,
845
+ loadConfig,
495
846
  parseEnvContent,
496
847
  parseEnvFile,
497
848
  scanFiles,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subramanyaks/env-drift",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Zero-config CLI and library to detect environment variable drift, missing keys, dead vars, and accidental public secret exposure.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -22,6 +22,7 @@
22
22
  "files": [
23
23
  "dist",
24
24
  "README.md",
25
+ "CHANGELOG.md",
25
26
  "LICENSE"
26
27
  ],
27
28
  "engines": {