@subramanyaks/env-drift 1.0.1 → 1.2.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/CHANGELOG.md +48 -0
- package/README.md +48 -11
- package/dist/cli.js +976 -79
- package/dist/index.cjs +867 -57
- package/dist/index.d.cts +127 -7
- package/dist/index.d.ts +127 -7
- package/dist/index.js +854 -56
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -4,28 +4,31 @@ import { resolve } from "path";
|
|
|
4
4
|
// src/envParser.ts
|
|
5
5
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
6
6
|
var ENV_LINE_REGEX = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
|
7
|
+
function parseDoubleQuotedValue(raw) {
|
|
8
|
+
let result = "";
|
|
9
|
+
for (let i = 1; i < raw.length; i++) {
|
|
10
|
+
const ch = raw[i];
|
|
11
|
+
if (ch === "\\" && i + 1 < raw.length) {
|
|
12
|
+
const next = raw[i + 1];
|
|
13
|
+
if (next === "n") result += "\n";
|
|
14
|
+
else if (next === "r") result += "\r";
|
|
15
|
+
else if (next === "t") result += " ";
|
|
16
|
+
else result += next;
|
|
17
|
+
i++;
|
|
18
|
+
} else if (ch === '"') {
|
|
19
|
+
return { value: result, closed: true };
|
|
20
|
+
} else {
|
|
21
|
+
result += ch;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return { value: result, closed: false };
|
|
25
|
+
}
|
|
7
26
|
function parseValue(raw) {
|
|
8
27
|
const trimmed = raw.trim();
|
|
9
28
|
if (!trimmed) return "";
|
|
10
29
|
const quote = trimmed[0];
|
|
11
30
|
if (quote === '"') {
|
|
12
|
-
|
|
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;
|
|
31
|
+
return parseDoubleQuotedValue(trimmed).value;
|
|
29
32
|
}
|
|
30
33
|
if (quote === "'") {
|
|
31
34
|
const closingIdx = trimmed.indexOf("'", 1);
|
|
@@ -45,8 +48,10 @@ function parseEnvContent(content) {
|
|
|
45
48
|
const seen = /* @__PURE__ */ new Set();
|
|
46
49
|
const duplicateSet = /* @__PURE__ */ new Set();
|
|
47
50
|
const values = {};
|
|
51
|
+
const keyLines = {};
|
|
48
52
|
const lines = content.split(/\r?\n/);
|
|
49
|
-
for (
|
|
53
|
+
for (let i = 0; i < lines.length; i++) {
|
|
54
|
+
const rawLine = lines[i];
|
|
50
55
|
const line = rawLine.trim();
|
|
51
56
|
if (!line || line.startsWith("#")) continue;
|
|
52
57
|
const match = ENV_LINE_REGEX.exec(line);
|
|
@@ -54,17 +59,33 @@ function parseEnvContent(content) {
|
|
|
54
59
|
const key = match[1];
|
|
55
60
|
const rawValue = match[2] ?? "";
|
|
56
61
|
if (!key) continue;
|
|
62
|
+
const startLine = i + 1;
|
|
57
63
|
if (seen.has(key)) {
|
|
58
64
|
duplicateSet.add(key);
|
|
59
65
|
} else {
|
|
60
66
|
seen.add(key);
|
|
61
67
|
keys.push(key);
|
|
62
68
|
}
|
|
63
|
-
|
|
69
|
+
const trimmedVal = rawValue.trimStart();
|
|
70
|
+
if (trimmedVal.startsWith('"')) {
|
|
71
|
+
let combined = trimmedVal;
|
|
72
|
+
let parsed = parseDoubleQuotedValue(combined);
|
|
73
|
+
while (!parsed.closed && i + 1 < lines.length) {
|
|
74
|
+
i++;
|
|
75
|
+
combined += `
|
|
76
|
+
${lines[i]}`;
|
|
77
|
+
parsed = parseDoubleQuotedValue(combined);
|
|
78
|
+
}
|
|
79
|
+
values[key] = parsed.value;
|
|
80
|
+
} else {
|
|
81
|
+
values[key] = parseValue(rawValue);
|
|
82
|
+
}
|
|
83
|
+
keyLines[key] = startLine;
|
|
64
84
|
}
|
|
65
85
|
return {
|
|
66
86
|
keys,
|
|
67
87
|
values,
|
|
88
|
+
lines: keyLines,
|
|
68
89
|
duplicates: Array.from(duplicateSet)
|
|
69
90
|
};
|
|
70
91
|
}
|
|
@@ -75,16 +96,18 @@ function parseEnvFile(filePath) {
|
|
|
75
96
|
exists: false,
|
|
76
97
|
keys: [],
|
|
77
98
|
values: {},
|
|
99
|
+
lines: {},
|
|
78
100
|
duplicates: []
|
|
79
101
|
};
|
|
80
102
|
}
|
|
81
103
|
const content = readFileSync(filePath, "utf-8");
|
|
82
|
-
const { keys, values, duplicates } = parseEnvContent(content);
|
|
104
|
+
const { keys, values, lines, duplicates } = parseEnvContent(content);
|
|
83
105
|
return {
|
|
84
106
|
filePath,
|
|
85
107
|
exists: true,
|
|
86
108
|
keys,
|
|
87
109
|
values,
|
|
110
|
+
lines,
|
|
88
111
|
duplicates
|
|
89
112
|
};
|
|
90
113
|
}
|
|
@@ -142,12 +165,109 @@ var DEFAULT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
142
165
|
".svelte",
|
|
143
166
|
".astro"
|
|
144
167
|
]);
|
|
168
|
+
var REGEX_PRECEDING_KEYWORDS = /* @__PURE__ */ new Set([
|
|
169
|
+
"return",
|
|
170
|
+
"case",
|
|
171
|
+
"throw",
|
|
172
|
+
"in",
|
|
173
|
+
"of",
|
|
174
|
+
"typeof",
|
|
175
|
+
"void",
|
|
176
|
+
"delete",
|
|
177
|
+
"await",
|
|
178
|
+
"yield",
|
|
179
|
+
"else",
|
|
180
|
+
"do"
|
|
181
|
+
]);
|
|
145
182
|
function stripCommentsPreservingLines(source) {
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
183
|
+
const out = [];
|
|
184
|
+
const len = source.length;
|
|
185
|
+
let i = 0;
|
|
186
|
+
let prevSignificant = "";
|
|
187
|
+
let prevWord = "";
|
|
188
|
+
while (i < len) {
|
|
189
|
+
const ch = source[i];
|
|
190
|
+
const next = i + 1 < len ? source[i + 1] : "";
|
|
191
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
192
|
+
const quote = ch;
|
|
193
|
+
out.push(ch);
|
|
194
|
+
i++;
|
|
195
|
+
while (i < len) {
|
|
196
|
+
const c = source[i];
|
|
197
|
+
out.push(c);
|
|
198
|
+
i++;
|
|
199
|
+
if (c === "\\" && i < len) {
|
|
200
|
+
out.push(source[i]);
|
|
201
|
+
i++;
|
|
202
|
+
} else if (c === quote) {
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
prevSignificant = quote;
|
|
207
|
+
prevWord = "";
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (ch === "/" && next === "/") {
|
|
211
|
+
out.push(" ", " ");
|
|
212
|
+
i += 2;
|
|
213
|
+
while (i < len && source[i] !== "\n" && source[i] !== "\r") {
|
|
214
|
+
out.push(" ");
|
|
215
|
+
i++;
|
|
216
|
+
}
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (ch === "/" && next === "*") {
|
|
220
|
+
out.push(" ", " ");
|
|
221
|
+
i += 2;
|
|
222
|
+
while (i < len) {
|
|
223
|
+
if (source[i] === "*" && i + 1 < len && source[i + 1] === "/") {
|
|
224
|
+
out.push(" ", " ");
|
|
225
|
+
i += 2;
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
const c = source[i];
|
|
229
|
+
out.push(c === "\n" || c === "\r" ? c : " ");
|
|
230
|
+
i++;
|
|
231
|
+
}
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if (ch === "/" && (prevSignificant === "" || "=([{,;:!&|?+-*%^~<>".includes(prevSignificant) || REGEX_PRECEDING_KEYWORDS.has(prevWord))) {
|
|
235
|
+
out.push(ch);
|
|
236
|
+
i++;
|
|
237
|
+
let inCharClass = false;
|
|
238
|
+
while (i < len) {
|
|
239
|
+
const c = source[i];
|
|
240
|
+
out.push(c);
|
|
241
|
+
i++;
|
|
242
|
+
if (c === "\\" && i < len) {
|
|
243
|
+
out.push(source[i]);
|
|
244
|
+
i++;
|
|
245
|
+
} else if (c === "[") {
|
|
246
|
+
inCharClass = true;
|
|
247
|
+
} else if (c === "]") {
|
|
248
|
+
inCharClass = false;
|
|
249
|
+
} else if (c === "/" && !inCharClass) {
|
|
250
|
+
break;
|
|
251
|
+
} else if (c === "\n" || c === "\r") {
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
prevSignificant = "/";
|
|
256
|
+
prevWord = "";
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
out.push(ch);
|
|
260
|
+
if (!/\s/.test(ch)) {
|
|
261
|
+
if (/[A-Za-z0-9_$]/.test(ch)) {
|
|
262
|
+
prevWord = /[A-Za-z0-9_$]/.test(prevSignificant) ? prevWord + ch : ch;
|
|
263
|
+
} else {
|
|
264
|
+
prevWord = "";
|
|
265
|
+
}
|
|
266
|
+
prevSignificant = ch;
|
|
267
|
+
}
|
|
268
|
+
i++;
|
|
269
|
+
}
|
|
270
|
+
return out.join("");
|
|
151
271
|
}
|
|
152
272
|
function getLineNumber(source, index) {
|
|
153
273
|
let line = 1;
|
|
@@ -156,35 +276,48 @@ function getLineNumber(source, index) {
|
|
|
156
276
|
}
|
|
157
277
|
return line;
|
|
158
278
|
}
|
|
279
|
+
function collectIgnoredLines(source) {
|
|
280
|
+
const ignored = /* @__PURE__ */ new Set();
|
|
281
|
+
const lines = source.split(/\r?\n/);
|
|
282
|
+
for (let i = 0; i < lines.length; i++) {
|
|
283
|
+
const line = lines[i];
|
|
284
|
+
if (/(?:\/\/|\/\*)\s*env-drift-ignore-next-line\b/.test(line)) {
|
|
285
|
+
ignored.add(i + 2);
|
|
286
|
+
} else if (/(?:\/\/|\/\*)\s*env-drift-ignore\b/.test(line)) {
|
|
287
|
+
ignored.add(i + 1);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return ignored;
|
|
291
|
+
}
|
|
159
292
|
function extractEnvReferences(content, filePath) {
|
|
293
|
+
const ignoredLines = collectIgnoredLines(content);
|
|
160
294
|
const cleaned = stripCommentsPreservingLines(content);
|
|
161
295
|
const refs = [];
|
|
162
296
|
const normalizedFile = filePath.replace(/\\/g, "/");
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
const source = match[1];
|
|
166
|
-
const name = match[2];
|
|
167
|
-
if (!name || match.index === void 0) continue;
|
|
297
|
+
const addRef = (name, line, source) => {
|
|
298
|
+
if (ignoredLines.has(line)) return;
|
|
168
299
|
refs.push({
|
|
169
300
|
name,
|
|
170
301
|
file: normalizedFile,
|
|
171
|
-
line
|
|
302
|
+
line,
|
|
172
303
|
source
|
|
173
304
|
});
|
|
305
|
+
};
|
|
306
|
+
const dotRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
|
|
307
|
+
for (const match of cleaned.matchAll(dotRegex)) {
|
|
308
|
+
const source = match[1];
|
|
309
|
+
const name = match[2];
|
|
310
|
+
if (!name || match.index === void 0) continue;
|
|
311
|
+
addRef(name, getLineNumber(cleaned, match.index), source);
|
|
174
312
|
}
|
|
175
|
-
const bracketRegex = /\b(process\.env|import\.meta\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
|
|
313
|
+
const bracketRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
|
|
176
314
|
for (const match of cleaned.matchAll(bracketRegex)) {
|
|
177
315
|
const source = match[1];
|
|
178
316
|
const name = match[2];
|
|
179
317
|
if (!name || match.index === void 0) continue;
|
|
180
|
-
|
|
181
|
-
name,
|
|
182
|
-
file: normalizedFile,
|
|
183
|
-
line: getLineNumber(cleaned, match.index),
|
|
184
|
-
source
|
|
185
|
-
});
|
|
318
|
+
addRef(name, getLineNumber(cleaned, match.index), source);
|
|
186
319
|
}
|
|
187
|
-
const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
|
|
320
|
+
const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env|Bun\.env)\b/g;
|
|
188
321
|
for (const match of cleaned.matchAll(destructureRegex)) {
|
|
189
322
|
const body = match[1];
|
|
190
323
|
const source = match[2];
|
|
@@ -201,14 +334,15 @@ function extractEnvReferences(content, filePath) {
|
|
|
201
334
|
if (!name) continue;
|
|
202
335
|
const leadingWs = part.indexOf(name);
|
|
203
336
|
const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
|
|
204
|
-
|
|
205
|
-
name,
|
|
206
|
-
file: normalizedFile,
|
|
207
|
-
line: getLineNumber(cleaned, absoluteIdx),
|
|
208
|
-
source
|
|
209
|
-
});
|
|
337
|
+
addRef(name, getLineNumber(cleaned, absoluteIdx), source);
|
|
210
338
|
}
|
|
211
339
|
}
|
|
340
|
+
const denoRegex = /\bDeno\.env\s*\??\.\s*get\s*\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\)/g;
|
|
341
|
+
for (const match of cleaned.matchAll(denoRegex)) {
|
|
342
|
+
const name = match[1];
|
|
343
|
+
if (!name || match.index === void 0) continue;
|
|
344
|
+
addRef(name, getLineNumber(cleaned, match.index), "Deno.env");
|
|
345
|
+
}
|
|
212
346
|
refs.sort((a, b) => a.line - b.line);
|
|
213
347
|
return refs;
|
|
214
348
|
}
|
|
@@ -276,12 +410,87 @@ var SENSITIVE_KEYWORDS = [
|
|
|
276
410
|
"SERVICE_ROLE",
|
|
277
411
|
"CREDENTIALS"
|
|
278
412
|
];
|
|
279
|
-
|
|
413
|
+
var PLACEHOLDER_VALUE_PATTERNS = [
|
|
414
|
+
/^your[_-]/i,
|
|
415
|
+
/^my[_-]/i,
|
|
416
|
+
/^change[_-]?me$/i,
|
|
417
|
+
/^replace[_-]?me$/i,
|
|
418
|
+
/^placeholder$/i,
|
|
419
|
+
/^example$/i,
|
|
420
|
+
/^dummy$/i,
|
|
421
|
+
/^test$/i,
|
|
422
|
+
/^todo$/i,
|
|
423
|
+
/^<[^>]+>$/,
|
|
424
|
+
/^\$\{[^}]+\}$/,
|
|
425
|
+
/^[xX*]{4,}$/
|
|
426
|
+
];
|
|
427
|
+
var PLACEHOLDER_URL_PASSWORDS = /* @__PURE__ */ new Set([
|
|
428
|
+
"password",
|
|
429
|
+
"pass",
|
|
430
|
+
"passwd",
|
|
431
|
+
"postgres",
|
|
432
|
+
"root",
|
|
433
|
+
"admin",
|
|
434
|
+
"changeme",
|
|
435
|
+
"change_me",
|
|
436
|
+
"secret",
|
|
437
|
+
"example",
|
|
438
|
+
"dummy",
|
|
439
|
+
"test",
|
|
440
|
+
"1234",
|
|
441
|
+
"123456",
|
|
442
|
+
"your_password",
|
|
443
|
+
"<password>"
|
|
444
|
+
]);
|
|
445
|
+
var EXAMPLE_SECRET_PATTERNS = [
|
|
446
|
+
{ pattern: /^sk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe live secret key" },
|
|
447
|
+
{ pattern: /^rk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe restricted live key" },
|
|
448
|
+
{ pattern: /^whsec_[A-Za-z0-9]{16,}$/, reason: "Stripe webhook secret" },
|
|
449
|
+
{ pattern: /^gh[pous]_[A-Za-z0-9]{20,}$/, reason: "GitHub access token" },
|
|
450
|
+
{ pattern: /^github_pat_[A-Za-z0-9_]{20,}$/, reason: "GitHub fine-grained token" },
|
|
451
|
+
{ pattern: /^AKIA[0-9A-Z]{16}$/, reason: "AWS Access Key ID" },
|
|
452
|
+
{ pattern: /^sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}$/, reason: "AI provider API key" },
|
|
453
|
+
{ pattern: /^sk-[A-Za-z0-9]{32,}$/, reason: "Secret API key (sk-...)" },
|
|
454
|
+
{ pattern: /^xox[baprs]-[A-Za-z0-9-]{10,}$/, reason: "Slack token" },
|
|
455
|
+
{ pattern: /^AIza[0-9A-Za-z_-]{35}$/, reason: "Google API key" },
|
|
456
|
+
{
|
|
457
|
+
pattern: /^eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}$/,
|
|
458
|
+
reason: "JWT token"
|
|
459
|
+
},
|
|
460
|
+
{
|
|
461
|
+
pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
462
|
+
reason: "PEM private key"
|
|
463
|
+
}
|
|
464
|
+
];
|
|
465
|
+
var CONNECTION_URL_PASSWORD_REGEX = /^(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^:\s/]+:([^@\s/]+)@/i;
|
|
466
|
+
function detectExampleSecretLeak(_name, value) {
|
|
467
|
+
const trimmed = value.trim();
|
|
468
|
+
if (!trimmed) return null;
|
|
469
|
+
if (PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(trimmed))) {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
for (const { pattern, reason } of EXAMPLE_SECRET_PATTERNS) {
|
|
473
|
+
if (pattern.test(trimmed)) {
|
|
474
|
+
return reason;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const urlMatch = CONNECTION_URL_PASSWORD_REGEX.exec(trimmed);
|
|
478
|
+
if (urlMatch) {
|
|
479
|
+
const password = urlMatch[1] ?? "";
|
|
480
|
+
if (password && !PLACEHOLDER_URL_PASSWORDS.has(password.toLowerCase()) && !PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(password))) {
|
|
481
|
+
return "Connection URL with embedded password";
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
function detectSecretExposure(name, options) {
|
|
280
487
|
const upper = name.toUpperCase();
|
|
281
|
-
const
|
|
488
|
+
const prefixes = options?.publicPrefixes?.length ? [...PUBLIC_ENV_PREFIXES, ...options.publicPrefixes.map((p) => p.toUpperCase())] : PUBLIC_ENV_PREFIXES;
|
|
489
|
+
const keywords = options?.sensitiveKeywords?.length ? [...SENSITIVE_KEYWORDS, ...options.sensitiveKeywords.map((k) => k.toUpperCase())] : SENSITIVE_KEYWORDS;
|
|
490
|
+
const prefix = prefixes.find((p) => upper.startsWith(p));
|
|
282
491
|
if (!prefix) return null;
|
|
283
492
|
const rest = upper.slice(prefix.length);
|
|
284
|
-
const matchedKeyword =
|
|
493
|
+
const matchedKeyword = keywords.find((kw) => rest.includes(kw));
|
|
285
494
|
if (!matchedKeyword) return null;
|
|
286
495
|
return { prefix, matchedKeyword };
|
|
287
496
|
}
|
|
@@ -290,7 +499,8 @@ function auditEnv(options = {}) {
|
|
|
290
499
|
const envFileName = options.envFile ?? ".env";
|
|
291
500
|
const exampleFileName = options.exampleFile ?? ".env.example";
|
|
292
501
|
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
293
|
-
const
|
|
502
|
+
const ignoreDirs = options.ignoreDirs?.length ? [...DEFAULT_IGNORE_DIRS, ...options.ignoreDirs] : void 0;
|
|
503
|
+
const { scannedFiles, references } = scanFiles(rootDir, { ignoreDirs });
|
|
294
504
|
const usedInCode = {};
|
|
295
505
|
for (const ref of references) {
|
|
296
506
|
if (!usedInCode[ref.name]) {
|
|
@@ -302,6 +512,7 @@ function auditEnv(options = {}) {
|
|
|
302
512
|
const parsedExample = parseEnvFile(resolve(rootDir, exampleFileName));
|
|
303
513
|
let envFileExists = parsedEnv.exists;
|
|
304
514
|
const localEnvKeys = new Set(parsedEnv.keys);
|
|
515
|
+
const localEnvValues = { ...parsedEnv.values };
|
|
305
516
|
if (!options.envFile) {
|
|
306
517
|
const parsedLocal = parseEnvFile(resolve(rootDir, ".env.local"));
|
|
307
518
|
if (parsedLocal.exists) {
|
|
@@ -309,6 +520,7 @@ function auditEnv(options = {}) {
|
|
|
309
520
|
}
|
|
310
521
|
for (const key of parsedLocal.keys) {
|
|
311
522
|
localEnvKeys.add(key);
|
|
523
|
+
localEnvValues[key] = parsedLocal.values[key] ?? "";
|
|
312
524
|
}
|
|
313
525
|
}
|
|
314
526
|
const exampleKeys = new Set(parsedExample.keys);
|
|
@@ -316,6 +528,9 @@ function auditEnv(options = {}) {
|
|
|
316
528
|
const codeKeySet = new Set(codeKeys);
|
|
317
529
|
const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
|
|
318
530
|
const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
|
|
531
|
+
const emptyInEnv = codeKeys.filter(
|
|
532
|
+
(k) => !ignoreSet.has(k) && localEnvKeys.has(k) && (localEnvValues[k] ?? "").trim() === ""
|
|
533
|
+
).sort();
|
|
319
534
|
const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
320
535
|
const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
321
536
|
const allKnownKeys = /* @__PURE__ */ new Set([
|
|
@@ -326,7 +541,10 @@ function auditEnv(options = {}) {
|
|
|
326
541
|
const secretExposures = [];
|
|
327
542
|
for (const key of Array.from(allKnownKeys).sort()) {
|
|
328
543
|
if (ignoreSet.has(key)) continue;
|
|
329
|
-
const hit = detectSecretExposure(key
|
|
544
|
+
const hit = detectSecretExposure(key, {
|
|
545
|
+
publicPrefixes: options.publicPrefixes,
|
|
546
|
+
sensitiveKeywords: options.sensitiveKeywords
|
|
547
|
+
});
|
|
330
548
|
if (hit) {
|
|
331
549
|
secretExposures.push({
|
|
332
550
|
name: key,
|
|
@@ -336,6 +554,19 @@ function auditEnv(options = {}) {
|
|
|
336
554
|
});
|
|
337
555
|
}
|
|
338
556
|
}
|
|
557
|
+
const exampleSecretLeaks = [];
|
|
558
|
+
for (const key of [...parsedExample.keys].sort()) {
|
|
559
|
+
if (ignoreSet.has(key)) continue;
|
|
560
|
+
const reason = detectExampleSecretLeak(key, parsedExample.values[key] ?? "");
|
|
561
|
+
if (reason) {
|
|
562
|
+
exampleSecretLeaks.push({
|
|
563
|
+
name: key,
|
|
564
|
+
reason,
|
|
565
|
+
file: exampleFileName,
|
|
566
|
+
line: parsedExample.lines[key] ?? 1
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
}
|
|
339
570
|
return {
|
|
340
571
|
rootDir,
|
|
341
572
|
scannedFiles,
|
|
@@ -344,9 +575,11 @@ function auditEnv(options = {}) {
|
|
|
344
575
|
usedInCode,
|
|
345
576
|
missingInEnv,
|
|
346
577
|
missingInExample,
|
|
578
|
+
emptyInEnv,
|
|
347
579
|
unusedInEnv,
|
|
348
580
|
unusedInExample,
|
|
349
581
|
secretExposures,
|
|
582
|
+
exampleSecretLeaks,
|
|
350
583
|
duplicateKeys: {
|
|
351
584
|
env: parsedEnv.duplicates,
|
|
352
585
|
example: parsedExample.duplicates
|
|
@@ -354,9 +587,168 @@ function auditEnv(options = {}) {
|
|
|
354
587
|
};
|
|
355
588
|
}
|
|
356
589
|
|
|
357
|
-
// src/
|
|
590
|
+
// src/config.ts
|
|
591
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
592
|
+
import { resolve as resolve2 } from "path";
|
|
593
|
+
function toStringArray(val) {
|
|
594
|
+
if (!Array.isArray(val)) return void 0;
|
|
595
|
+
return val.filter((item) => typeof item === "string" && item.trim().length > 0);
|
|
596
|
+
}
|
|
597
|
+
function normalizeConfig(raw) {
|
|
598
|
+
if (!raw || typeof raw !== "object") return {};
|
|
599
|
+
const obj = raw;
|
|
600
|
+
const config = {};
|
|
601
|
+
if (typeof obj.envFile === "string" && obj.envFile.trim()) {
|
|
602
|
+
config.envFile = obj.envFile.trim();
|
|
603
|
+
}
|
|
604
|
+
if (typeof obj.exampleFile === "string" && obj.exampleFile.trim()) {
|
|
605
|
+
config.exampleFile = obj.exampleFile.trim();
|
|
606
|
+
}
|
|
607
|
+
const ignore = toStringArray(obj.ignore);
|
|
608
|
+
if (ignore) config.ignore = ignore;
|
|
609
|
+
const ignoreDirs = toStringArray(obj.ignoreDirs);
|
|
610
|
+
if (ignoreDirs) config.ignoreDirs = ignoreDirs;
|
|
611
|
+
const publicPrefixes = toStringArray(obj.publicPrefixes);
|
|
612
|
+
if (publicPrefixes) config.publicPrefixes = publicPrefixes;
|
|
613
|
+
const sensitiveKeywords = toStringArray(obj.sensitiveKeywords);
|
|
614
|
+
if (sensitiveKeywords) config.sensitiveKeywords = sensitiveKeywords;
|
|
615
|
+
if (typeof obj.strict === "boolean") {
|
|
616
|
+
config.strict = obj.strict;
|
|
617
|
+
}
|
|
618
|
+
return config;
|
|
619
|
+
}
|
|
620
|
+
function loadConfig(rootDir) {
|
|
621
|
+
const rcPath = resolve2(rootDir, ".envdriftrc.json");
|
|
622
|
+
if (existsSync2(rcPath)) {
|
|
623
|
+
try {
|
|
624
|
+
const parsed = JSON.parse(readFileSync3(rcPath, "utf-8"));
|
|
625
|
+
return normalizeConfig(parsed);
|
|
626
|
+
} catch (err) {
|
|
627
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
628
|
+
throw new Error(`Failed to parse .envdriftrc.json: ${msg}`);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
const pkgPath = resolve2(rootDir, "package.json");
|
|
632
|
+
if (existsSync2(pkgPath)) {
|
|
633
|
+
try {
|
|
634
|
+
const parsed = JSON.parse(readFileSync3(pkgPath, "utf-8"));
|
|
635
|
+
if (parsed && typeof parsed === "object" && parsed["env-drift"]) {
|
|
636
|
+
return normalizeConfig(parsed["env-drift"]);
|
|
637
|
+
}
|
|
638
|
+
} catch {
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return {};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/diff.ts
|
|
645
|
+
import { resolve as resolve3 } from "path";
|
|
646
|
+
function diffEnvFiles(fileA, fileB, options = {}) {
|
|
647
|
+
const rootDir = resolve3(options.rootDir ?? process.cwd());
|
|
648
|
+
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
649
|
+
const parsedA = parseEnvFile(resolve3(rootDir, fileA));
|
|
650
|
+
const parsedB = parseEnvFile(resolve3(rootDir, fileB));
|
|
651
|
+
const keysA = parsedA.keys.filter((k) => !ignoreSet.has(k));
|
|
652
|
+
const keysB = parsedB.keys.filter((k) => !ignoreSet.has(k));
|
|
653
|
+
const setA = new Set(keysA);
|
|
654
|
+
const setB = new Set(keysB);
|
|
655
|
+
const onlyInA = keysA.filter((k) => !setB.has(k)).sort();
|
|
656
|
+
const onlyInB = keysB.filter((k) => !setA.has(k)).sort();
|
|
657
|
+
const inBoth = keysA.filter((k) => setB.has(k)).sort();
|
|
658
|
+
const emptyInA = keysA.filter((k) => (parsedA.values[k] ?? "").trim() === "").sort();
|
|
659
|
+
const emptyInB = keysB.filter((k) => (parsedB.values[k] ?? "").trim() === "").sort();
|
|
660
|
+
return {
|
|
661
|
+
fileA,
|
|
662
|
+
fileB,
|
|
663
|
+
fileAExists: parsedA.exists,
|
|
664
|
+
fileBExists: parsedB.exists,
|
|
665
|
+
onlyInA,
|
|
666
|
+
onlyInB,
|
|
667
|
+
inBoth,
|
|
668
|
+
emptyInA,
|
|
669
|
+
emptyInB
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function hasDiffIssues(diff, options = {}) {
|
|
673
|
+
if (!diff.fileAExists || !diff.fileBExists) return true;
|
|
674
|
+
if (diff.onlyInA.length > 0 || diff.onlyInB.length > 0) return true;
|
|
675
|
+
if (options.strict && (diff.emptyInA.length > 0 || diff.emptyInB.length > 0)) {
|
|
676
|
+
return true;
|
|
677
|
+
}
|
|
678
|
+
return false;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// src/schemagen.ts
|
|
358
682
|
import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
|
|
359
683
|
import { dirname } from "path";
|
|
684
|
+
function inferZodRule(key) {
|
|
685
|
+
if (key === "NODE_ENV") {
|
|
686
|
+
return 'z.enum(["development", "production", "test"]).default("development")';
|
|
687
|
+
}
|
|
688
|
+
if (/(?:^|_)(?:URL|URI|ENDPOINT)$/i.test(key)) {
|
|
689
|
+
return "z.string().url()";
|
|
690
|
+
}
|
|
691
|
+
if (/^(?:PORT|.*_PORT|.*_TIMEOUT|.*_MS|.*_SECONDS)$/i.test(key)) {
|
|
692
|
+
return "z.coerce.number()";
|
|
693
|
+
}
|
|
694
|
+
if (/^(?:ENABLE|DISABLE|IS|HAS|USE)_|_(?:ENABLED|DISABLED)$/i.test(key)) {
|
|
695
|
+
return "z.coerce.boolean()";
|
|
696
|
+
}
|
|
697
|
+
return "z.string().min(1)";
|
|
698
|
+
}
|
|
699
|
+
function generateZodSchema(result) {
|
|
700
|
+
const keys = /* @__PURE__ */ new Set();
|
|
701
|
+
let hasProcessOrServer = false;
|
|
702
|
+
let hasImportMeta = false;
|
|
703
|
+
for (const [key, refs] of Object.entries(result.usedInCode)) {
|
|
704
|
+
if (BUILTIN_ENV_VARS.has(key)) continue;
|
|
705
|
+
keys.add(key);
|
|
706
|
+
for (const ref of refs) {
|
|
707
|
+
if (ref.source === "import.meta.env") {
|
|
708
|
+
hasImportMeta = true;
|
|
709
|
+
} else {
|
|
710
|
+
hasProcessOrServer = true;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
for (const key of result.unusedInExample) {
|
|
715
|
+
if (!BUILTIN_ENV_VARS.has(key)) {
|
|
716
|
+
keys.add(key);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
const sortedKeys = Array.from(keys).sort();
|
|
720
|
+
const sourceExpr = hasImportMeta && !hasProcessOrServer ? "import.meta.env" : "process.env";
|
|
721
|
+
const lines = [
|
|
722
|
+
"// Auto-generated by env-drift. Customize validators as needed.",
|
|
723
|
+
'import { z } from "zod";',
|
|
724
|
+
"",
|
|
725
|
+
"export const envSchema = z.object({"
|
|
726
|
+
];
|
|
727
|
+
for (const key of sortedKeys) {
|
|
728
|
+
lines.push(` ${key}: ${inferZodRule(key)},`);
|
|
729
|
+
}
|
|
730
|
+
lines.push("});");
|
|
731
|
+
lines.push("");
|
|
732
|
+
lines.push("export type Env = z.infer<typeof envSchema>;");
|
|
733
|
+
lines.push("");
|
|
734
|
+
lines.push(`export const env = envSchema.parse(${sourceExpr});`);
|
|
735
|
+
lines.push("");
|
|
736
|
+
return lines.join("\n");
|
|
737
|
+
}
|
|
738
|
+
function writeZodSchema(outputPath, result) {
|
|
739
|
+
const content = generateZodSchema(result);
|
|
740
|
+
mkdirSync(dirname(outputPath), { recursive: true });
|
|
741
|
+
writeFileSync2(outputPath, content, "utf-8");
|
|
742
|
+
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
743
|
+
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
744
|
+
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
745
|
+
]);
|
|
746
|
+
return { outputPath, count: uniqueKeys.size };
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// src/typegen.ts
|
|
750
|
+
import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
751
|
+
import { dirname as dirname2 } from "path";
|
|
360
752
|
function generateEnvTypes(result) {
|
|
361
753
|
const processKeys = /* @__PURE__ */ new Set();
|
|
362
754
|
const importMetaKeys = /* @__PURE__ */ new Set();
|
|
@@ -411,8 +803,8 @@ function generateEnvTypes(result) {
|
|
|
411
803
|
}
|
|
412
804
|
function writeEnvTypes(outputPath, result) {
|
|
413
805
|
const content = generateEnvTypes(result);
|
|
414
|
-
|
|
415
|
-
|
|
806
|
+
mkdirSync2(dirname2(outputPath), { recursive: true });
|
|
807
|
+
writeFileSync3(outputPath, content, "utf-8");
|
|
416
808
|
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
417
809
|
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
418
810
|
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
@@ -421,6 +813,7 @@ function writeEnvTypes(outputPath, result) {
|
|
|
421
813
|
}
|
|
422
814
|
|
|
423
815
|
// src/reporter.ts
|
|
816
|
+
import { relative as relative2 } from "path";
|
|
424
817
|
import pc from "picocolors";
|
|
425
818
|
function formatRefs(refs) {
|
|
426
819
|
if (!refs || refs.length === 0) return "";
|
|
@@ -430,7 +823,12 @@ function formatRefs(refs) {
|
|
|
430
823
|
}
|
|
431
824
|
function hasBlockingIssues(result, options = {}) {
|
|
432
825
|
const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
|
|
433
|
-
|
|
826
|
+
const baseBlocking = checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
|
|
827
|
+
if (baseBlocking) return true;
|
|
828
|
+
if (options.strict) {
|
|
829
|
+
return result.emptyInEnv.length > 0 || result.unusedInEnv.length > 0 || result.unusedInExample.length > 0 || result.duplicateKeys.env.length > 0 || result.duplicateKeys.example.length > 0;
|
|
830
|
+
}
|
|
831
|
+
return false;
|
|
434
832
|
}
|
|
435
833
|
function formatAuditReport(result, options = {}) {
|
|
436
834
|
const envFile = options.envFile ?? ".env";
|
|
@@ -444,7 +842,7 @@ function formatAuditReport(result, options = {}) {
|
|
|
444
842
|
)}`
|
|
445
843
|
);
|
|
446
844
|
lines.push("");
|
|
447
|
-
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;
|
|
845
|
+
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;
|
|
448
846
|
if (totalIssues === 0) {
|
|
449
847
|
lines.push(pc.green("\u2714 No environment drift detected. Everything is in sync!"));
|
|
450
848
|
if (skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
@@ -466,6 +864,19 @@ function formatAuditReport(result, options = {}) {
|
|
|
466
864
|
}
|
|
467
865
|
lines.push("");
|
|
468
866
|
}
|
|
867
|
+
if (result.exampleSecretLeaks.length > 0) {
|
|
868
|
+
lines.push(
|
|
869
|
+
pc.bold(pc.red(`\u2716 Possible Real Secret in ${exampleFile} (${result.exampleSecretLeaks.length})`))
|
|
870
|
+
);
|
|
871
|
+
for (const item of result.exampleSecretLeaks) {
|
|
872
|
+
lines.push(
|
|
873
|
+
` ${pc.red("\u2022")} ${pc.bold(item.name)} ${pc.dim(
|
|
874
|
+
`(${item.reason}) \u2190 ${item.file}:${item.line}`
|
|
875
|
+
)}`
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
lines.push("");
|
|
879
|
+
}
|
|
469
880
|
if (!skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
470
881
|
lines.push(pc.bold(pc.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
|
|
471
882
|
for (const key of result.missingInEnv) {
|
|
@@ -485,6 +896,13 @@ function formatAuditReport(result, options = {}) {
|
|
|
485
896
|
}
|
|
486
897
|
lines.push("");
|
|
487
898
|
}
|
|
899
|
+
if (result.emptyInEnv.length > 0) {
|
|
900
|
+
lines.push(pc.bold(pc.yellow(`\u26A0 Empty Value in ${envFile} (${result.emptyInEnv.length})`)));
|
|
901
|
+
for (const key of result.emptyInEnv) {
|
|
902
|
+
lines.push(` ${pc.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
|
|
903
|
+
}
|
|
904
|
+
lines.push("");
|
|
905
|
+
}
|
|
488
906
|
if (result.unusedInEnv.length > 0) {
|
|
489
907
|
lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
|
|
490
908
|
for (const key of result.unusedInEnv) {
|
|
@@ -517,6 +935,374 @@ function formatAuditReport(result, options = {}) {
|
|
|
517
935
|
}
|
|
518
936
|
return lines.join("\n");
|
|
519
937
|
}
|
|
938
|
+
function escapeGitHubData(value) {
|
|
939
|
+
return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
940
|
+
}
|
|
941
|
+
function escapeGitHubProperty(value) {
|
|
942
|
+
return escapeGitHubData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
|
|
943
|
+
}
|
|
944
|
+
function buildAnnotation(level, title, message, file, line) {
|
|
945
|
+
const props = [];
|
|
946
|
+
if (file) props.push(`file=${escapeGitHubProperty(file)}`);
|
|
947
|
+
if (line !== void 0) props.push(`line=${line}`);
|
|
948
|
+
props.push(`title=${escapeGitHubProperty(title)}`);
|
|
949
|
+
return `::${level} ${props.join(",")}::${escapeGitHubData(message)}`;
|
|
950
|
+
}
|
|
951
|
+
function formatGitHubAnnotations(result, options = {}) {
|
|
952
|
+
const envFile = options.envFile ?? ".env";
|
|
953
|
+
const exampleFile = options.exampleFile ?? ".env.example";
|
|
954
|
+
const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
|
|
955
|
+
const lines = [];
|
|
956
|
+
for (const item of result.secretExposures) {
|
|
957
|
+
const firstRef = item.references[0];
|
|
958
|
+
lines.push(
|
|
959
|
+
buildAnnotation(
|
|
960
|
+
"error",
|
|
961
|
+
"Public Secret Exposure",
|
|
962
|
+
`${item.name} uses client-exposed prefix "${item.prefix}" with sensitive keyword "${item.matchedKeyword}"`,
|
|
963
|
+
firstRef?.file,
|
|
964
|
+
firstRef?.line
|
|
965
|
+
)
|
|
966
|
+
);
|
|
967
|
+
}
|
|
968
|
+
for (const leak of result.exampleSecretLeaks) {
|
|
969
|
+
lines.push(
|
|
970
|
+
buildAnnotation(
|
|
971
|
+
"error",
|
|
972
|
+
`Secret Leak in ${exampleFile}`,
|
|
973
|
+
`${leak.name} appears to contain a real secret (${leak.reason}). Replace it with an empty placeholder.`,
|
|
974
|
+
leak.file,
|
|
975
|
+
leak.line
|
|
976
|
+
)
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
if (!skipMissingInEnv) {
|
|
980
|
+
for (const key of result.missingInEnv) {
|
|
981
|
+
const firstRef = result.usedInCode[key]?.[0];
|
|
982
|
+
lines.push(
|
|
983
|
+
buildAnnotation(
|
|
984
|
+
"error",
|
|
985
|
+
`Missing in ${envFile}`,
|
|
986
|
+
`Environment variable ${key} is referenced in code but missing in ${envFile}`,
|
|
987
|
+
firstRef?.file,
|
|
988
|
+
firstRef?.line
|
|
989
|
+
)
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
for (const key of result.missingInExample) {
|
|
994
|
+
const firstRef = result.usedInCode[key]?.[0];
|
|
995
|
+
lines.push(
|
|
996
|
+
buildAnnotation(
|
|
997
|
+
"error",
|
|
998
|
+
`Missing in ${exampleFile}`,
|
|
999
|
+
`Environment variable ${key} is referenced in code but missing in ${exampleFile}. Run \`env-drift --sync\` to update.`,
|
|
1000
|
+
firstRef?.file,
|
|
1001
|
+
firstRef?.line
|
|
1002
|
+
)
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
for (const key of result.emptyInEnv) {
|
|
1006
|
+
const firstRef = result.usedInCode[key]?.[0];
|
|
1007
|
+
lines.push(
|
|
1008
|
+
buildAnnotation(
|
|
1009
|
+
"warning",
|
|
1010
|
+
`Empty Value in ${envFile}`,
|
|
1011
|
+
`Environment variable ${key} is defined in ${envFile} with an empty value`,
|
|
1012
|
+
firstRef?.file,
|
|
1013
|
+
firstRef?.line
|
|
1014
|
+
)
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
for (const key of result.unusedInEnv) {
|
|
1018
|
+
lines.push(
|
|
1019
|
+
buildAnnotation(
|
|
1020
|
+
"warning",
|
|
1021
|
+
`Unused in ${envFile}`,
|
|
1022
|
+
`Environment variable ${key} is defined in ${envFile} but not referenced in code`,
|
|
1023
|
+
envFile
|
|
1024
|
+
)
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
for (const key of result.unusedInExample) {
|
|
1028
|
+
lines.push(
|
|
1029
|
+
buildAnnotation(
|
|
1030
|
+
"warning",
|
|
1031
|
+
`Unused in ${exampleFile}`,
|
|
1032
|
+
`Environment variable ${key} is defined in ${exampleFile} but not referenced in code`,
|
|
1033
|
+
exampleFile
|
|
1034
|
+
)
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
for (const key of result.duplicateKeys.env) {
|
|
1038
|
+
lines.push(
|
|
1039
|
+
buildAnnotation(
|
|
1040
|
+
"warning",
|
|
1041
|
+
`Duplicate Key in ${envFile}`,
|
|
1042
|
+
`Environment variable ${key} is defined multiple times in ${envFile}`,
|
|
1043
|
+
envFile
|
|
1044
|
+
)
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
for (const key of result.duplicateKeys.example) {
|
|
1048
|
+
lines.push(
|
|
1049
|
+
buildAnnotation(
|
|
1050
|
+
"warning",
|
|
1051
|
+
`Duplicate Key in ${exampleFile}`,
|
|
1052
|
+
`Environment variable ${key} is defined multiple times in ${exampleFile}`,
|
|
1053
|
+
exampleFile
|
|
1054
|
+
)
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
return lines.join("\n");
|
|
1058
|
+
}
|
|
1059
|
+
function formatDiffReport(diff) {
|
|
1060
|
+
const lines = [];
|
|
1061
|
+
lines.push("");
|
|
1062
|
+
lines.push(
|
|
1063
|
+
`${pc.bold(pc.cyan("env-drift diff"))} ${pc.dim(`\u2014 ${diff.fileA} \u2194 ${diff.fileB}`)}`
|
|
1064
|
+
);
|
|
1065
|
+
lines.push("");
|
|
1066
|
+
if (!diff.fileAExists) {
|
|
1067
|
+
lines.push(pc.red(`\u2716 File not found: ${diff.fileA}`));
|
|
1068
|
+
}
|
|
1069
|
+
if (!diff.fileBExists) {
|
|
1070
|
+
lines.push(pc.red(`\u2716 File not found: ${diff.fileB}`));
|
|
1071
|
+
}
|
|
1072
|
+
if (!diff.fileAExists || !diff.fileBExists) {
|
|
1073
|
+
lines.push("");
|
|
1074
|
+
return lines.join("\n");
|
|
1075
|
+
}
|
|
1076
|
+
const totalIssues = diff.onlyInA.length + diff.onlyInB.length + diff.emptyInA.length + diff.emptyInB.length;
|
|
1077
|
+
if (totalIssues === 0) {
|
|
1078
|
+
lines.push(
|
|
1079
|
+
pc.green(
|
|
1080
|
+
`\u2714 No drift between ${diff.fileA} and ${diff.fileB} (${diff.inBoth.length} shared key${diff.inBoth.length === 1 ? "" : "s"}).`
|
|
1081
|
+
)
|
|
1082
|
+
);
|
|
1083
|
+
lines.push("");
|
|
1084
|
+
return lines.join("\n");
|
|
1085
|
+
}
|
|
1086
|
+
if (diff.onlyInA.length > 0) {
|
|
1087
|
+
lines.push(
|
|
1088
|
+
pc.bold(pc.red(`\u2716 Only in ${diff.fileA} (missing in ${diff.fileB}) (${diff.onlyInA.length})`))
|
|
1089
|
+
);
|
|
1090
|
+
for (const key of diff.onlyInA) {
|
|
1091
|
+
lines.push(` ${pc.red("\u2022")} ${key}`);
|
|
1092
|
+
}
|
|
1093
|
+
lines.push("");
|
|
1094
|
+
}
|
|
1095
|
+
if (diff.onlyInB.length > 0) {
|
|
1096
|
+
lines.push(
|
|
1097
|
+
pc.bold(pc.red(`\u2716 Only in ${diff.fileB} (missing in ${diff.fileA}) (${diff.onlyInB.length})`))
|
|
1098
|
+
);
|
|
1099
|
+
for (const key of diff.onlyInB) {
|
|
1100
|
+
lines.push(` ${pc.red("\u2022")} ${key}`);
|
|
1101
|
+
}
|
|
1102
|
+
lines.push("");
|
|
1103
|
+
}
|
|
1104
|
+
if (diff.emptyInA.length > 0) {
|
|
1105
|
+
lines.push(pc.bold(pc.yellow(`\u26A0 Empty in ${diff.fileA} (${diff.emptyInA.length})`)));
|
|
1106
|
+
for (const key of diff.emptyInA) {
|
|
1107
|
+
lines.push(` ${pc.yellow("\u2022")} ${key}`);
|
|
1108
|
+
}
|
|
1109
|
+
lines.push("");
|
|
1110
|
+
}
|
|
1111
|
+
if (diff.emptyInB.length > 0) {
|
|
1112
|
+
lines.push(pc.bold(pc.yellow(`\u26A0 Empty in ${diff.fileB} (${diff.emptyInB.length})`)));
|
|
1113
|
+
for (const key of diff.emptyInB) {
|
|
1114
|
+
lines.push(` ${pc.yellow("\u2022")} ${key}`);
|
|
1115
|
+
}
|
|
1116
|
+
lines.push("");
|
|
1117
|
+
}
|
|
1118
|
+
lines.push(pc.dim(`Shared keys in both files: ${diff.inBoth.length}`));
|
|
1119
|
+
lines.push("");
|
|
1120
|
+
return lines.join("\n");
|
|
1121
|
+
}
|
|
1122
|
+
function formatWorkspaceReport(wsResult, options = {}) {
|
|
1123
|
+
const lines = [];
|
|
1124
|
+
lines.push("");
|
|
1125
|
+
lines.push(
|
|
1126
|
+
`${pc.bold(pc.cyan("env-drift workspaces"))} ${pc.dim(
|
|
1127
|
+
`\u2014 audited ${wsResult.workspaces.length} workspace${wsResult.workspaces.length === 1 ? "" : "s"}`
|
|
1128
|
+
)}`
|
|
1129
|
+
);
|
|
1130
|
+
if (wsResult.workspaces.length === 0) {
|
|
1131
|
+
lines.push("");
|
|
1132
|
+
lines.push(pc.yellow("\u26A0 No workspaces found in package.json or pnpm-workspace.yaml."));
|
|
1133
|
+
lines.push("");
|
|
1134
|
+
return lines.join("\n");
|
|
1135
|
+
}
|
|
1136
|
+
for (const ws of wsResult.workspaces) {
|
|
1137
|
+
const rel = relative2(wsResult.rootDir, ws.path).replace(/\\/g, "/");
|
|
1138
|
+
lines.push("");
|
|
1139
|
+
lines.push(pc.bold(pc.white(`\u25B8 ${ws.name}`)) + pc.dim(` (${rel})`));
|
|
1140
|
+
lines.push(formatAuditReport(ws.result, options).trimEnd());
|
|
1141
|
+
}
|
|
1142
|
+
lines.push("");
|
|
1143
|
+
return lines.join("\n");
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
// src/workspaces.ts
|
|
1147
|
+
import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
|
|
1148
|
+
import { join as join2, relative as relative3, resolve as resolve4 } from "path";
|
|
1149
|
+
function readWorkspacePatterns(rootDir) {
|
|
1150
|
+
const pkgPath = resolve4(rootDir, "package.json");
|
|
1151
|
+
if (existsSync3(pkgPath)) {
|
|
1152
|
+
try {
|
|
1153
|
+
const parsed = JSON.parse(readFileSync4(pkgPath, "utf-8"));
|
|
1154
|
+
if (Array.isArray(parsed.workspaces)) {
|
|
1155
|
+
return parsed.workspaces.filter((p) => typeof p === "string");
|
|
1156
|
+
}
|
|
1157
|
+
if (parsed.workspaces && typeof parsed.workspaces === "object" && Array.isArray(parsed.workspaces.packages)) {
|
|
1158
|
+
return parsed.workspaces.packages.filter((p) => typeof p === "string");
|
|
1159
|
+
}
|
|
1160
|
+
} catch {
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
const pnpmPath = resolve4(rootDir, "pnpm-workspace.yaml");
|
|
1164
|
+
if (existsSync3(pnpmPath)) {
|
|
1165
|
+
const content = readFileSync4(pnpmPath, "utf-8");
|
|
1166
|
+
const patterns = [];
|
|
1167
|
+
let inPackages = false;
|
|
1168
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
1169
|
+
const line = rawLine.trim();
|
|
1170
|
+
if (!line || line.startsWith("#")) continue;
|
|
1171
|
+
if (/^packages\s*:/.test(line)) {
|
|
1172
|
+
inPackages = true;
|
|
1173
|
+
continue;
|
|
1174
|
+
}
|
|
1175
|
+
if (inPackages) {
|
|
1176
|
+
if (line.startsWith("-")) {
|
|
1177
|
+
const item = line.slice(1).trim().replace(/^["']|["']$/g, "");
|
|
1178
|
+
if (item) patterns.push(item);
|
|
1179
|
+
} else if (/^[A-Za-z0-9_-]+\s*:/.test(line)) {
|
|
1180
|
+
inPackages = false;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
if (patterns.length > 0) return patterns;
|
|
1185
|
+
}
|
|
1186
|
+
return [];
|
|
1187
|
+
}
|
|
1188
|
+
function expandPattern(rootDir, pattern) {
|
|
1189
|
+
const cleaned = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
1190
|
+
const segments = cleaned.split("/").filter(Boolean);
|
|
1191
|
+
let currentDirs = [rootDir];
|
|
1192
|
+
for (const seg of segments) {
|
|
1193
|
+
const nextDirs = [];
|
|
1194
|
+
if (seg === "*" || seg === "**") {
|
|
1195
|
+
for (const dir of currentDirs) {
|
|
1196
|
+
if (!existsSync3(dir)) continue;
|
|
1197
|
+
for (const entry of readdirSync2(dir, { withFileTypes: true })) {
|
|
1198
|
+
if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
|
|
1199
|
+
nextDirs.push(join2(dir, entry.name));
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
} else if (seg.includes("*")) {
|
|
1204
|
+
const regex = new RegExp(
|
|
1205
|
+
"^" + seg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$"
|
|
1206
|
+
);
|
|
1207
|
+
for (const dir of currentDirs) {
|
|
1208
|
+
if (!existsSync3(dir)) continue;
|
|
1209
|
+
for (const entry of readdirSync2(dir, { withFileTypes: true })) {
|
|
1210
|
+
if (entry.isDirectory() && regex.test(entry.name)) {
|
|
1211
|
+
nextDirs.push(join2(dir, entry.name));
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
} else {
|
|
1216
|
+
for (const dir of currentDirs) {
|
|
1217
|
+
const candidate = join2(dir, seg);
|
|
1218
|
+
if (existsSync3(candidate) && statSync2(candidate).isDirectory()) {
|
|
1219
|
+
nextDirs.push(candidate);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
currentDirs = nextDirs;
|
|
1224
|
+
}
|
|
1225
|
+
return currentDirs;
|
|
1226
|
+
}
|
|
1227
|
+
function discoverWorkspaces(rootDir) {
|
|
1228
|
+
const resolvedRoot = resolve4(rootDir);
|
|
1229
|
+
const patterns = readWorkspacePatterns(resolvedRoot);
|
|
1230
|
+
if (patterns.length === 0) return [];
|
|
1231
|
+
const included = /* @__PURE__ */ new Set();
|
|
1232
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
1233
|
+
for (const pattern of patterns) {
|
|
1234
|
+
if (pattern.startsWith("!")) {
|
|
1235
|
+
for (const dir of expandPattern(resolvedRoot, pattern.slice(1))) {
|
|
1236
|
+
excluded.add(resolve4(dir));
|
|
1237
|
+
}
|
|
1238
|
+
} else {
|
|
1239
|
+
for (const dir of expandPattern(resolvedRoot, pattern)) {
|
|
1240
|
+
included.add(resolve4(dir));
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
const results = [];
|
|
1245
|
+
for (const dir of included) {
|
|
1246
|
+
if (excluded.has(dir)) continue;
|
|
1247
|
+
const relPath = relative3(resolvedRoot, dir).replace(/\\/g, "/");
|
|
1248
|
+
let name = relPath;
|
|
1249
|
+
const pkgPath = join2(dir, "package.json");
|
|
1250
|
+
if (existsSync3(pkgPath)) {
|
|
1251
|
+
try {
|
|
1252
|
+
const pkg = JSON.parse(readFileSync4(pkgPath, "utf-8"));
|
|
1253
|
+
if (typeof pkg.name === "string" && pkg.name.trim()) {
|
|
1254
|
+
name = pkg.name.trim();
|
|
1255
|
+
}
|
|
1256
|
+
} catch {
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
results.push({ name, path: dir });
|
|
1260
|
+
}
|
|
1261
|
+
results.sort((a, b) => a.path.localeCompare(b.path));
|
|
1262
|
+
return results;
|
|
1263
|
+
}
|
|
1264
|
+
function auditWorkspaces(rootDir, options = {}) {
|
|
1265
|
+
const resolvedRoot = resolve4(rootDir);
|
|
1266
|
+
const discovered = discoverWorkspaces(resolvedRoot);
|
|
1267
|
+
const workspaces = [];
|
|
1268
|
+
for (const ws of discovered) {
|
|
1269
|
+
const wsConfig = loadConfig(ws.path);
|
|
1270
|
+
const mergedIgnore = [
|
|
1271
|
+
...options.ignore ?? [],
|
|
1272
|
+
...wsConfig.ignore ?? []
|
|
1273
|
+
];
|
|
1274
|
+
const mergedIgnoreDirs = [
|
|
1275
|
+
...options.ignoreDirs ?? [],
|
|
1276
|
+
...wsConfig.ignoreDirs ?? []
|
|
1277
|
+
];
|
|
1278
|
+
const mergedPrefixes = [
|
|
1279
|
+
...options.publicPrefixes ?? [],
|
|
1280
|
+
...wsConfig.publicPrefixes ?? []
|
|
1281
|
+
];
|
|
1282
|
+
const mergedKeywords = [
|
|
1283
|
+
...options.sensitiveKeywords ?? [],
|
|
1284
|
+
...wsConfig.sensitiveKeywords ?? []
|
|
1285
|
+
];
|
|
1286
|
+
const result = auditEnv({
|
|
1287
|
+
rootDir: ws.path,
|
|
1288
|
+
envFile: options.envFile ?? wsConfig.envFile,
|
|
1289
|
+
exampleFile: options.exampleFile ?? wsConfig.exampleFile,
|
|
1290
|
+
ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
|
|
1291
|
+
ignoreDirs: mergedIgnoreDirs.length > 0 ? mergedIgnoreDirs : void 0,
|
|
1292
|
+
publicPrefixes: mergedPrefixes.length > 0 ? mergedPrefixes : void 0,
|
|
1293
|
+
sensitiveKeywords: mergedKeywords.length > 0 ? mergedKeywords : void 0
|
|
1294
|
+
});
|
|
1295
|
+
workspaces.push({
|
|
1296
|
+
name: ws.name,
|
|
1297
|
+
path: ws.path,
|
|
1298
|
+
result
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
return {
|
|
1302
|
+
rootDir: resolvedRoot,
|
|
1303
|
+
workspaces
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
520
1306
|
export {
|
|
521
1307
|
BUILTIN_ENV_VARS,
|
|
522
1308
|
DEFAULT_EXTENSIONS,
|
|
@@ -524,14 +1310,26 @@ export {
|
|
|
524
1310
|
PUBLIC_ENV_PREFIXES,
|
|
525
1311
|
SENSITIVE_KEYWORDS,
|
|
526
1312
|
auditEnv,
|
|
1313
|
+
auditWorkspaces,
|
|
1314
|
+
detectExampleSecretLeak,
|
|
527
1315
|
detectSecretExposure,
|
|
1316
|
+
diffEnvFiles,
|
|
1317
|
+
discoverWorkspaces,
|
|
528
1318
|
extractEnvReferences,
|
|
529
1319
|
formatAuditReport,
|
|
1320
|
+
formatDiffReport,
|
|
1321
|
+
formatGitHubAnnotations,
|
|
1322
|
+
formatWorkspaceReport,
|
|
530
1323
|
generateEnvTypes,
|
|
1324
|
+
generateZodSchema,
|
|
531
1325
|
hasBlockingIssues,
|
|
1326
|
+
hasDiffIssues,
|
|
1327
|
+
inferZodRule,
|
|
1328
|
+
loadConfig,
|
|
532
1329
|
parseEnvContent,
|
|
533
1330
|
parseEnvFile,
|
|
534
1331
|
scanFiles,
|
|
535
1332
|
syncEnvExample,
|
|
536
|
-
writeEnvTypes
|
|
1333
|
+
writeEnvTypes,
|
|
1334
|
+
writeZodSchema
|
|
537
1335
|
};
|