@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.cjs
CHANGED
|
@@ -36,16 +36,28 @@ __export(src_exports, {
|
|
|
36
36
|
PUBLIC_ENV_PREFIXES: () => PUBLIC_ENV_PREFIXES,
|
|
37
37
|
SENSITIVE_KEYWORDS: () => SENSITIVE_KEYWORDS,
|
|
38
38
|
auditEnv: () => auditEnv,
|
|
39
|
+
auditWorkspaces: () => auditWorkspaces,
|
|
40
|
+
detectExampleSecretLeak: () => detectExampleSecretLeak,
|
|
39
41
|
detectSecretExposure: () => detectSecretExposure,
|
|
42
|
+
diffEnvFiles: () => diffEnvFiles,
|
|
43
|
+
discoverWorkspaces: () => discoverWorkspaces,
|
|
40
44
|
extractEnvReferences: () => extractEnvReferences,
|
|
41
45
|
formatAuditReport: () => formatAuditReport,
|
|
46
|
+
formatDiffReport: () => formatDiffReport,
|
|
47
|
+
formatGitHubAnnotations: () => formatGitHubAnnotations,
|
|
48
|
+
formatWorkspaceReport: () => formatWorkspaceReport,
|
|
42
49
|
generateEnvTypes: () => generateEnvTypes,
|
|
50
|
+
generateZodSchema: () => generateZodSchema,
|
|
43
51
|
hasBlockingIssues: () => hasBlockingIssues,
|
|
52
|
+
hasDiffIssues: () => hasDiffIssues,
|
|
53
|
+
inferZodRule: () => inferZodRule,
|
|
54
|
+
loadConfig: () => loadConfig,
|
|
44
55
|
parseEnvContent: () => parseEnvContent,
|
|
45
56
|
parseEnvFile: () => parseEnvFile,
|
|
46
57
|
scanFiles: () => scanFiles,
|
|
47
58
|
syncEnvExample: () => syncEnvExample,
|
|
48
|
-
writeEnvTypes: () => writeEnvTypes
|
|
59
|
+
writeEnvTypes: () => writeEnvTypes,
|
|
60
|
+
writeZodSchema: () => writeZodSchema
|
|
49
61
|
});
|
|
50
62
|
module.exports = __toCommonJS(src_exports);
|
|
51
63
|
|
|
@@ -55,28 +67,31 @@ var import_node_path2 = require("path");
|
|
|
55
67
|
// src/envParser.ts
|
|
56
68
|
var import_node_fs = require("fs");
|
|
57
69
|
var ENV_LINE_REGEX = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
|
70
|
+
function parseDoubleQuotedValue(raw) {
|
|
71
|
+
let result = "";
|
|
72
|
+
for (let i = 1; i < raw.length; i++) {
|
|
73
|
+
const ch = raw[i];
|
|
74
|
+
if (ch === "\\" && i + 1 < raw.length) {
|
|
75
|
+
const next = raw[i + 1];
|
|
76
|
+
if (next === "n") result += "\n";
|
|
77
|
+
else if (next === "r") result += "\r";
|
|
78
|
+
else if (next === "t") result += " ";
|
|
79
|
+
else result += next;
|
|
80
|
+
i++;
|
|
81
|
+
} else if (ch === '"') {
|
|
82
|
+
return { value: result, closed: true };
|
|
83
|
+
} else {
|
|
84
|
+
result += ch;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { value: result, closed: false };
|
|
88
|
+
}
|
|
58
89
|
function parseValue(raw) {
|
|
59
90
|
const trimmed = raw.trim();
|
|
60
91
|
if (!trimmed) return "";
|
|
61
92
|
const quote = trimmed[0];
|
|
62
93
|
if (quote === '"') {
|
|
63
|
-
|
|
64
|
-
for (let i = 1; i < trimmed.length; i++) {
|
|
65
|
-
const ch = trimmed[i];
|
|
66
|
-
if (ch === "\\" && i + 1 < trimmed.length) {
|
|
67
|
-
const next = trimmed[i + 1];
|
|
68
|
-
if (next === "n") result += "\n";
|
|
69
|
-
else if (next === "r") result += "\r";
|
|
70
|
-
else if (next === "t") result += " ";
|
|
71
|
-
else result += next;
|
|
72
|
-
i++;
|
|
73
|
-
} else if (ch === '"') {
|
|
74
|
-
return result;
|
|
75
|
-
} else {
|
|
76
|
-
result += ch;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return result;
|
|
94
|
+
return parseDoubleQuotedValue(trimmed).value;
|
|
80
95
|
}
|
|
81
96
|
if (quote === "'") {
|
|
82
97
|
const closingIdx = trimmed.indexOf("'", 1);
|
|
@@ -96,8 +111,10 @@ function parseEnvContent(content) {
|
|
|
96
111
|
const seen = /* @__PURE__ */ new Set();
|
|
97
112
|
const duplicateSet = /* @__PURE__ */ new Set();
|
|
98
113
|
const values = {};
|
|
114
|
+
const keyLines = {};
|
|
99
115
|
const lines = content.split(/\r?\n/);
|
|
100
|
-
for (
|
|
116
|
+
for (let i = 0; i < lines.length; i++) {
|
|
117
|
+
const rawLine = lines[i];
|
|
101
118
|
const line = rawLine.trim();
|
|
102
119
|
if (!line || line.startsWith("#")) continue;
|
|
103
120
|
const match = ENV_LINE_REGEX.exec(line);
|
|
@@ -105,17 +122,33 @@ function parseEnvContent(content) {
|
|
|
105
122
|
const key = match[1];
|
|
106
123
|
const rawValue = match[2] ?? "";
|
|
107
124
|
if (!key) continue;
|
|
125
|
+
const startLine = i + 1;
|
|
108
126
|
if (seen.has(key)) {
|
|
109
127
|
duplicateSet.add(key);
|
|
110
128
|
} else {
|
|
111
129
|
seen.add(key);
|
|
112
130
|
keys.push(key);
|
|
113
131
|
}
|
|
114
|
-
|
|
132
|
+
const trimmedVal = rawValue.trimStart();
|
|
133
|
+
if (trimmedVal.startsWith('"')) {
|
|
134
|
+
let combined = trimmedVal;
|
|
135
|
+
let parsed = parseDoubleQuotedValue(combined);
|
|
136
|
+
while (!parsed.closed && i + 1 < lines.length) {
|
|
137
|
+
i++;
|
|
138
|
+
combined += `
|
|
139
|
+
${lines[i]}`;
|
|
140
|
+
parsed = parseDoubleQuotedValue(combined);
|
|
141
|
+
}
|
|
142
|
+
values[key] = parsed.value;
|
|
143
|
+
} else {
|
|
144
|
+
values[key] = parseValue(rawValue);
|
|
145
|
+
}
|
|
146
|
+
keyLines[key] = startLine;
|
|
115
147
|
}
|
|
116
148
|
return {
|
|
117
149
|
keys,
|
|
118
150
|
values,
|
|
151
|
+
lines: keyLines,
|
|
119
152
|
duplicates: Array.from(duplicateSet)
|
|
120
153
|
};
|
|
121
154
|
}
|
|
@@ -126,16 +159,18 @@ function parseEnvFile(filePath) {
|
|
|
126
159
|
exists: false,
|
|
127
160
|
keys: [],
|
|
128
161
|
values: {},
|
|
162
|
+
lines: {},
|
|
129
163
|
duplicates: []
|
|
130
164
|
};
|
|
131
165
|
}
|
|
132
166
|
const content = (0, import_node_fs.readFileSync)(filePath, "utf-8");
|
|
133
|
-
const { keys, values, duplicates } = parseEnvContent(content);
|
|
167
|
+
const { keys, values, lines, duplicates } = parseEnvContent(content);
|
|
134
168
|
return {
|
|
135
169
|
filePath,
|
|
136
170
|
exists: true,
|
|
137
171
|
keys,
|
|
138
172
|
values,
|
|
173
|
+
lines,
|
|
139
174
|
duplicates
|
|
140
175
|
};
|
|
141
176
|
}
|
|
@@ -193,12 +228,109 @@ var DEFAULT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
193
228
|
".svelte",
|
|
194
229
|
".astro"
|
|
195
230
|
]);
|
|
231
|
+
var REGEX_PRECEDING_KEYWORDS = /* @__PURE__ */ new Set([
|
|
232
|
+
"return",
|
|
233
|
+
"case",
|
|
234
|
+
"throw",
|
|
235
|
+
"in",
|
|
236
|
+
"of",
|
|
237
|
+
"typeof",
|
|
238
|
+
"void",
|
|
239
|
+
"delete",
|
|
240
|
+
"await",
|
|
241
|
+
"yield",
|
|
242
|
+
"else",
|
|
243
|
+
"do"
|
|
244
|
+
]);
|
|
196
245
|
function stripCommentsPreservingLines(source) {
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
246
|
+
const out = [];
|
|
247
|
+
const len = source.length;
|
|
248
|
+
let i = 0;
|
|
249
|
+
let prevSignificant = "";
|
|
250
|
+
let prevWord = "";
|
|
251
|
+
while (i < len) {
|
|
252
|
+
const ch = source[i];
|
|
253
|
+
const next = i + 1 < len ? source[i + 1] : "";
|
|
254
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
255
|
+
const quote = ch;
|
|
256
|
+
out.push(ch);
|
|
257
|
+
i++;
|
|
258
|
+
while (i < len) {
|
|
259
|
+
const c = source[i];
|
|
260
|
+
out.push(c);
|
|
261
|
+
i++;
|
|
262
|
+
if (c === "\\" && i < len) {
|
|
263
|
+
out.push(source[i]);
|
|
264
|
+
i++;
|
|
265
|
+
} else if (c === quote) {
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
prevSignificant = quote;
|
|
270
|
+
prevWord = "";
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (ch === "/" && next === "/") {
|
|
274
|
+
out.push(" ", " ");
|
|
275
|
+
i += 2;
|
|
276
|
+
while (i < len && source[i] !== "\n" && source[i] !== "\r") {
|
|
277
|
+
out.push(" ");
|
|
278
|
+
i++;
|
|
279
|
+
}
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (ch === "/" && next === "*") {
|
|
283
|
+
out.push(" ", " ");
|
|
284
|
+
i += 2;
|
|
285
|
+
while (i < len) {
|
|
286
|
+
if (source[i] === "*" && i + 1 < len && source[i + 1] === "/") {
|
|
287
|
+
out.push(" ", " ");
|
|
288
|
+
i += 2;
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
const c = source[i];
|
|
292
|
+
out.push(c === "\n" || c === "\r" ? c : " ");
|
|
293
|
+
i++;
|
|
294
|
+
}
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (ch === "/" && (prevSignificant === "" || "=([{,;:!&|?+-*%^~<>".includes(prevSignificant) || REGEX_PRECEDING_KEYWORDS.has(prevWord))) {
|
|
298
|
+
out.push(ch);
|
|
299
|
+
i++;
|
|
300
|
+
let inCharClass = false;
|
|
301
|
+
while (i < len) {
|
|
302
|
+
const c = source[i];
|
|
303
|
+
out.push(c);
|
|
304
|
+
i++;
|
|
305
|
+
if (c === "\\" && i < len) {
|
|
306
|
+
out.push(source[i]);
|
|
307
|
+
i++;
|
|
308
|
+
} else if (c === "[") {
|
|
309
|
+
inCharClass = true;
|
|
310
|
+
} else if (c === "]") {
|
|
311
|
+
inCharClass = false;
|
|
312
|
+
} else if (c === "/" && !inCharClass) {
|
|
313
|
+
break;
|
|
314
|
+
} else if (c === "\n" || c === "\r") {
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
prevSignificant = "/";
|
|
319
|
+
prevWord = "";
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
out.push(ch);
|
|
323
|
+
if (!/\s/.test(ch)) {
|
|
324
|
+
if (/[A-Za-z0-9_$]/.test(ch)) {
|
|
325
|
+
prevWord = /[A-Za-z0-9_$]/.test(prevSignificant) ? prevWord + ch : ch;
|
|
326
|
+
} else {
|
|
327
|
+
prevWord = "";
|
|
328
|
+
}
|
|
329
|
+
prevSignificant = ch;
|
|
330
|
+
}
|
|
331
|
+
i++;
|
|
332
|
+
}
|
|
333
|
+
return out.join("");
|
|
202
334
|
}
|
|
203
335
|
function getLineNumber(source, index) {
|
|
204
336
|
let line = 1;
|
|
@@ -207,35 +339,48 @@ function getLineNumber(source, index) {
|
|
|
207
339
|
}
|
|
208
340
|
return line;
|
|
209
341
|
}
|
|
342
|
+
function collectIgnoredLines(source) {
|
|
343
|
+
const ignored = /* @__PURE__ */ new Set();
|
|
344
|
+
const lines = source.split(/\r?\n/);
|
|
345
|
+
for (let i = 0; i < lines.length; i++) {
|
|
346
|
+
const line = lines[i];
|
|
347
|
+
if (/(?:\/\/|\/\*)\s*env-drift-ignore-next-line\b/.test(line)) {
|
|
348
|
+
ignored.add(i + 2);
|
|
349
|
+
} else if (/(?:\/\/|\/\*)\s*env-drift-ignore\b/.test(line)) {
|
|
350
|
+
ignored.add(i + 1);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return ignored;
|
|
354
|
+
}
|
|
210
355
|
function extractEnvReferences(content, filePath) {
|
|
356
|
+
const ignoredLines = collectIgnoredLines(content);
|
|
211
357
|
const cleaned = stripCommentsPreservingLines(content);
|
|
212
358
|
const refs = [];
|
|
213
359
|
const normalizedFile = filePath.replace(/\\/g, "/");
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
const source = match[1];
|
|
217
|
-
const name = match[2];
|
|
218
|
-
if (!name || match.index === void 0) continue;
|
|
360
|
+
const addRef = (name, line, source) => {
|
|
361
|
+
if (ignoredLines.has(line)) return;
|
|
219
362
|
refs.push({
|
|
220
363
|
name,
|
|
221
364
|
file: normalizedFile,
|
|
222
|
-
line
|
|
365
|
+
line,
|
|
223
366
|
source
|
|
224
367
|
});
|
|
368
|
+
};
|
|
369
|
+
const dotRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
|
|
370
|
+
for (const match of cleaned.matchAll(dotRegex)) {
|
|
371
|
+
const source = match[1];
|
|
372
|
+
const name = match[2];
|
|
373
|
+
if (!name || match.index === void 0) continue;
|
|
374
|
+
addRef(name, getLineNumber(cleaned, match.index), source);
|
|
225
375
|
}
|
|
226
|
-
const bracketRegex = /\b(process\.env|import\.meta\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
|
|
376
|
+
const bracketRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
|
|
227
377
|
for (const match of cleaned.matchAll(bracketRegex)) {
|
|
228
378
|
const source = match[1];
|
|
229
379
|
const name = match[2];
|
|
230
380
|
if (!name || match.index === void 0) continue;
|
|
231
|
-
|
|
232
|
-
name,
|
|
233
|
-
file: normalizedFile,
|
|
234
|
-
line: getLineNumber(cleaned, match.index),
|
|
235
|
-
source
|
|
236
|
-
});
|
|
381
|
+
addRef(name, getLineNumber(cleaned, match.index), source);
|
|
237
382
|
}
|
|
238
|
-
const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
|
|
383
|
+
const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env|Bun\.env)\b/g;
|
|
239
384
|
for (const match of cleaned.matchAll(destructureRegex)) {
|
|
240
385
|
const body = match[1];
|
|
241
386
|
const source = match[2];
|
|
@@ -252,14 +397,15 @@ function extractEnvReferences(content, filePath) {
|
|
|
252
397
|
if (!name) continue;
|
|
253
398
|
const leadingWs = part.indexOf(name);
|
|
254
399
|
const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
|
|
255
|
-
|
|
256
|
-
name,
|
|
257
|
-
file: normalizedFile,
|
|
258
|
-
line: getLineNumber(cleaned, absoluteIdx),
|
|
259
|
-
source
|
|
260
|
-
});
|
|
400
|
+
addRef(name, getLineNumber(cleaned, absoluteIdx), source);
|
|
261
401
|
}
|
|
262
402
|
}
|
|
403
|
+
const denoRegex = /\bDeno\.env\s*\??\.\s*get\s*\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\)/g;
|
|
404
|
+
for (const match of cleaned.matchAll(denoRegex)) {
|
|
405
|
+
const name = match[1];
|
|
406
|
+
if (!name || match.index === void 0) continue;
|
|
407
|
+
addRef(name, getLineNumber(cleaned, match.index), "Deno.env");
|
|
408
|
+
}
|
|
263
409
|
refs.sort((a, b) => a.line - b.line);
|
|
264
410
|
return refs;
|
|
265
411
|
}
|
|
@@ -327,12 +473,87 @@ var SENSITIVE_KEYWORDS = [
|
|
|
327
473
|
"SERVICE_ROLE",
|
|
328
474
|
"CREDENTIALS"
|
|
329
475
|
];
|
|
330
|
-
|
|
476
|
+
var PLACEHOLDER_VALUE_PATTERNS = [
|
|
477
|
+
/^your[_-]/i,
|
|
478
|
+
/^my[_-]/i,
|
|
479
|
+
/^change[_-]?me$/i,
|
|
480
|
+
/^replace[_-]?me$/i,
|
|
481
|
+
/^placeholder$/i,
|
|
482
|
+
/^example$/i,
|
|
483
|
+
/^dummy$/i,
|
|
484
|
+
/^test$/i,
|
|
485
|
+
/^todo$/i,
|
|
486
|
+
/^<[^>]+>$/,
|
|
487
|
+
/^\$\{[^}]+\}$/,
|
|
488
|
+
/^[xX*]{4,}$/
|
|
489
|
+
];
|
|
490
|
+
var PLACEHOLDER_URL_PASSWORDS = /* @__PURE__ */ new Set([
|
|
491
|
+
"password",
|
|
492
|
+
"pass",
|
|
493
|
+
"passwd",
|
|
494
|
+
"postgres",
|
|
495
|
+
"root",
|
|
496
|
+
"admin",
|
|
497
|
+
"changeme",
|
|
498
|
+
"change_me",
|
|
499
|
+
"secret",
|
|
500
|
+
"example",
|
|
501
|
+
"dummy",
|
|
502
|
+
"test",
|
|
503
|
+
"1234",
|
|
504
|
+
"123456",
|
|
505
|
+
"your_password",
|
|
506
|
+
"<password>"
|
|
507
|
+
]);
|
|
508
|
+
var EXAMPLE_SECRET_PATTERNS = [
|
|
509
|
+
{ pattern: /^sk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe live secret key" },
|
|
510
|
+
{ pattern: /^rk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe restricted live key" },
|
|
511
|
+
{ pattern: /^whsec_[A-Za-z0-9]{16,}$/, reason: "Stripe webhook secret" },
|
|
512
|
+
{ pattern: /^gh[pous]_[A-Za-z0-9]{20,}$/, reason: "GitHub access token" },
|
|
513
|
+
{ pattern: /^github_pat_[A-Za-z0-9_]{20,}$/, reason: "GitHub fine-grained token" },
|
|
514
|
+
{ pattern: /^AKIA[0-9A-Z]{16}$/, reason: "AWS Access Key ID" },
|
|
515
|
+
{ pattern: /^sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}$/, reason: "AI provider API key" },
|
|
516
|
+
{ pattern: /^sk-[A-Za-z0-9]{32,}$/, reason: "Secret API key (sk-...)" },
|
|
517
|
+
{ pattern: /^xox[baprs]-[A-Za-z0-9-]{10,}$/, reason: "Slack token" },
|
|
518
|
+
{ pattern: /^AIza[0-9A-Za-z_-]{35}$/, reason: "Google API key" },
|
|
519
|
+
{
|
|
520
|
+
pattern: /^eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}$/,
|
|
521
|
+
reason: "JWT token"
|
|
522
|
+
},
|
|
523
|
+
{
|
|
524
|
+
pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
525
|
+
reason: "PEM private key"
|
|
526
|
+
}
|
|
527
|
+
];
|
|
528
|
+
var CONNECTION_URL_PASSWORD_REGEX = /^(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^:\s/]+:([^@\s/]+)@/i;
|
|
529
|
+
function detectExampleSecretLeak(_name, value) {
|
|
530
|
+
const trimmed = value.trim();
|
|
531
|
+
if (!trimmed) return null;
|
|
532
|
+
if (PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(trimmed))) {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
for (const { pattern, reason } of EXAMPLE_SECRET_PATTERNS) {
|
|
536
|
+
if (pattern.test(trimmed)) {
|
|
537
|
+
return reason;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const urlMatch = CONNECTION_URL_PASSWORD_REGEX.exec(trimmed);
|
|
541
|
+
if (urlMatch) {
|
|
542
|
+
const password = urlMatch[1] ?? "";
|
|
543
|
+
if (password && !PLACEHOLDER_URL_PASSWORDS.has(password.toLowerCase()) && !PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(password))) {
|
|
544
|
+
return "Connection URL with embedded password";
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return null;
|
|
548
|
+
}
|
|
549
|
+
function detectSecretExposure(name, options) {
|
|
331
550
|
const upper = name.toUpperCase();
|
|
332
|
-
const
|
|
551
|
+
const prefixes = options?.publicPrefixes?.length ? [...PUBLIC_ENV_PREFIXES, ...options.publicPrefixes.map((p) => p.toUpperCase())] : PUBLIC_ENV_PREFIXES;
|
|
552
|
+
const keywords = options?.sensitiveKeywords?.length ? [...SENSITIVE_KEYWORDS, ...options.sensitiveKeywords.map((k) => k.toUpperCase())] : SENSITIVE_KEYWORDS;
|
|
553
|
+
const prefix = prefixes.find((p) => upper.startsWith(p));
|
|
333
554
|
if (!prefix) return null;
|
|
334
555
|
const rest = upper.slice(prefix.length);
|
|
335
|
-
const matchedKeyword =
|
|
556
|
+
const matchedKeyword = keywords.find((kw) => rest.includes(kw));
|
|
336
557
|
if (!matchedKeyword) return null;
|
|
337
558
|
return { prefix, matchedKeyword };
|
|
338
559
|
}
|
|
@@ -341,7 +562,8 @@ function auditEnv(options = {}) {
|
|
|
341
562
|
const envFileName = options.envFile ?? ".env";
|
|
342
563
|
const exampleFileName = options.exampleFile ?? ".env.example";
|
|
343
564
|
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
344
|
-
const
|
|
565
|
+
const ignoreDirs = options.ignoreDirs?.length ? [...DEFAULT_IGNORE_DIRS, ...options.ignoreDirs] : void 0;
|
|
566
|
+
const { scannedFiles, references } = scanFiles(rootDir, { ignoreDirs });
|
|
345
567
|
const usedInCode = {};
|
|
346
568
|
for (const ref of references) {
|
|
347
569
|
if (!usedInCode[ref.name]) {
|
|
@@ -353,6 +575,7 @@ function auditEnv(options = {}) {
|
|
|
353
575
|
const parsedExample = parseEnvFile((0, import_node_path2.resolve)(rootDir, exampleFileName));
|
|
354
576
|
let envFileExists = parsedEnv.exists;
|
|
355
577
|
const localEnvKeys = new Set(parsedEnv.keys);
|
|
578
|
+
const localEnvValues = { ...parsedEnv.values };
|
|
356
579
|
if (!options.envFile) {
|
|
357
580
|
const parsedLocal = parseEnvFile((0, import_node_path2.resolve)(rootDir, ".env.local"));
|
|
358
581
|
if (parsedLocal.exists) {
|
|
@@ -360,6 +583,7 @@ function auditEnv(options = {}) {
|
|
|
360
583
|
}
|
|
361
584
|
for (const key of parsedLocal.keys) {
|
|
362
585
|
localEnvKeys.add(key);
|
|
586
|
+
localEnvValues[key] = parsedLocal.values[key] ?? "";
|
|
363
587
|
}
|
|
364
588
|
}
|
|
365
589
|
const exampleKeys = new Set(parsedExample.keys);
|
|
@@ -367,6 +591,9 @@ function auditEnv(options = {}) {
|
|
|
367
591
|
const codeKeySet = new Set(codeKeys);
|
|
368
592
|
const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
|
|
369
593
|
const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
|
|
594
|
+
const emptyInEnv = codeKeys.filter(
|
|
595
|
+
(k) => !ignoreSet.has(k) && localEnvKeys.has(k) && (localEnvValues[k] ?? "").trim() === ""
|
|
596
|
+
).sort();
|
|
370
597
|
const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
371
598
|
const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
372
599
|
const allKnownKeys = /* @__PURE__ */ new Set([
|
|
@@ -377,7 +604,10 @@ function auditEnv(options = {}) {
|
|
|
377
604
|
const secretExposures = [];
|
|
378
605
|
for (const key of Array.from(allKnownKeys).sort()) {
|
|
379
606
|
if (ignoreSet.has(key)) continue;
|
|
380
|
-
const hit = detectSecretExposure(key
|
|
607
|
+
const hit = detectSecretExposure(key, {
|
|
608
|
+
publicPrefixes: options.publicPrefixes,
|
|
609
|
+
sensitiveKeywords: options.sensitiveKeywords
|
|
610
|
+
});
|
|
381
611
|
if (hit) {
|
|
382
612
|
secretExposures.push({
|
|
383
613
|
name: key,
|
|
@@ -387,6 +617,19 @@ function auditEnv(options = {}) {
|
|
|
387
617
|
});
|
|
388
618
|
}
|
|
389
619
|
}
|
|
620
|
+
const exampleSecretLeaks = [];
|
|
621
|
+
for (const key of [...parsedExample.keys].sort()) {
|
|
622
|
+
if (ignoreSet.has(key)) continue;
|
|
623
|
+
const reason = detectExampleSecretLeak(key, parsedExample.values[key] ?? "");
|
|
624
|
+
if (reason) {
|
|
625
|
+
exampleSecretLeaks.push({
|
|
626
|
+
name: key,
|
|
627
|
+
reason,
|
|
628
|
+
file: exampleFileName,
|
|
629
|
+
line: parsedExample.lines[key] ?? 1
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
}
|
|
390
633
|
return {
|
|
391
634
|
rootDir,
|
|
392
635
|
scannedFiles,
|
|
@@ -395,9 +638,11 @@ function auditEnv(options = {}) {
|
|
|
395
638
|
usedInCode,
|
|
396
639
|
missingInEnv,
|
|
397
640
|
missingInExample,
|
|
641
|
+
emptyInEnv,
|
|
398
642
|
unusedInEnv,
|
|
399
643
|
unusedInExample,
|
|
400
644
|
secretExposures,
|
|
645
|
+
exampleSecretLeaks,
|
|
401
646
|
duplicateKeys: {
|
|
402
647
|
env: parsedEnv.duplicates,
|
|
403
648
|
example: parsedExample.duplicates
|
|
@@ -405,9 +650,168 @@ function auditEnv(options = {}) {
|
|
|
405
650
|
};
|
|
406
651
|
}
|
|
407
652
|
|
|
408
|
-
// src/
|
|
653
|
+
// src/config.ts
|
|
409
654
|
var import_node_fs3 = require("fs");
|
|
410
655
|
var import_node_path3 = require("path");
|
|
656
|
+
function toStringArray(val) {
|
|
657
|
+
if (!Array.isArray(val)) return void 0;
|
|
658
|
+
return val.filter((item) => typeof item === "string" && item.trim().length > 0);
|
|
659
|
+
}
|
|
660
|
+
function normalizeConfig(raw) {
|
|
661
|
+
if (!raw || typeof raw !== "object") return {};
|
|
662
|
+
const obj = raw;
|
|
663
|
+
const config = {};
|
|
664
|
+
if (typeof obj.envFile === "string" && obj.envFile.trim()) {
|
|
665
|
+
config.envFile = obj.envFile.trim();
|
|
666
|
+
}
|
|
667
|
+
if (typeof obj.exampleFile === "string" && obj.exampleFile.trim()) {
|
|
668
|
+
config.exampleFile = obj.exampleFile.trim();
|
|
669
|
+
}
|
|
670
|
+
const ignore = toStringArray(obj.ignore);
|
|
671
|
+
if (ignore) config.ignore = ignore;
|
|
672
|
+
const ignoreDirs = toStringArray(obj.ignoreDirs);
|
|
673
|
+
if (ignoreDirs) config.ignoreDirs = ignoreDirs;
|
|
674
|
+
const publicPrefixes = toStringArray(obj.publicPrefixes);
|
|
675
|
+
if (publicPrefixes) config.publicPrefixes = publicPrefixes;
|
|
676
|
+
const sensitiveKeywords = toStringArray(obj.sensitiveKeywords);
|
|
677
|
+
if (sensitiveKeywords) config.sensitiveKeywords = sensitiveKeywords;
|
|
678
|
+
if (typeof obj.strict === "boolean") {
|
|
679
|
+
config.strict = obj.strict;
|
|
680
|
+
}
|
|
681
|
+
return config;
|
|
682
|
+
}
|
|
683
|
+
function loadConfig(rootDir) {
|
|
684
|
+
const rcPath = (0, import_node_path3.resolve)(rootDir, ".envdriftrc.json");
|
|
685
|
+
if ((0, import_node_fs3.existsSync)(rcPath)) {
|
|
686
|
+
try {
|
|
687
|
+
const parsed = JSON.parse((0, import_node_fs3.readFileSync)(rcPath, "utf-8"));
|
|
688
|
+
return normalizeConfig(parsed);
|
|
689
|
+
} catch (err) {
|
|
690
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
691
|
+
throw new Error(`Failed to parse .envdriftrc.json: ${msg}`);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const pkgPath = (0, import_node_path3.resolve)(rootDir, "package.json");
|
|
695
|
+
if ((0, import_node_fs3.existsSync)(pkgPath)) {
|
|
696
|
+
try {
|
|
697
|
+
const parsed = JSON.parse((0, import_node_fs3.readFileSync)(pkgPath, "utf-8"));
|
|
698
|
+
if (parsed && typeof parsed === "object" && parsed["env-drift"]) {
|
|
699
|
+
return normalizeConfig(parsed["env-drift"]);
|
|
700
|
+
}
|
|
701
|
+
} catch {
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return {};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// src/diff.ts
|
|
708
|
+
var import_node_path4 = require("path");
|
|
709
|
+
function diffEnvFiles(fileA, fileB, options = {}) {
|
|
710
|
+
const rootDir = (0, import_node_path4.resolve)(options.rootDir ?? process.cwd());
|
|
711
|
+
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
712
|
+
const parsedA = parseEnvFile((0, import_node_path4.resolve)(rootDir, fileA));
|
|
713
|
+
const parsedB = parseEnvFile((0, import_node_path4.resolve)(rootDir, fileB));
|
|
714
|
+
const keysA = parsedA.keys.filter((k) => !ignoreSet.has(k));
|
|
715
|
+
const keysB = parsedB.keys.filter((k) => !ignoreSet.has(k));
|
|
716
|
+
const setA = new Set(keysA);
|
|
717
|
+
const setB = new Set(keysB);
|
|
718
|
+
const onlyInA = keysA.filter((k) => !setB.has(k)).sort();
|
|
719
|
+
const onlyInB = keysB.filter((k) => !setA.has(k)).sort();
|
|
720
|
+
const inBoth = keysA.filter((k) => setB.has(k)).sort();
|
|
721
|
+
const emptyInA = keysA.filter((k) => (parsedA.values[k] ?? "").trim() === "").sort();
|
|
722
|
+
const emptyInB = keysB.filter((k) => (parsedB.values[k] ?? "").trim() === "").sort();
|
|
723
|
+
return {
|
|
724
|
+
fileA,
|
|
725
|
+
fileB,
|
|
726
|
+
fileAExists: parsedA.exists,
|
|
727
|
+
fileBExists: parsedB.exists,
|
|
728
|
+
onlyInA,
|
|
729
|
+
onlyInB,
|
|
730
|
+
inBoth,
|
|
731
|
+
emptyInA,
|
|
732
|
+
emptyInB
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function hasDiffIssues(diff, options = {}) {
|
|
736
|
+
if (!diff.fileAExists || !diff.fileBExists) return true;
|
|
737
|
+
if (diff.onlyInA.length > 0 || diff.onlyInB.length > 0) return true;
|
|
738
|
+
if (options.strict && (diff.emptyInA.length > 0 || diff.emptyInB.length > 0)) {
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// src/schemagen.ts
|
|
745
|
+
var import_node_fs4 = require("fs");
|
|
746
|
+
var import_node_path5 = require("path");
|
|
747
|
+
function inferZodRule(key) {
|
|
748
|
+
if (key === "NODE_ENV") {
|
|
749
|
+
return 'z.enum(["development", "production", "test"]).default("development")';
|
|
750
|
+
}
|
|
751
|
+
if (/(?:^|_)(?:URL|URI|ENDPOINT)$/i.test(key)) {
|
|
752
|
+
return "z.string().url()";
|
|
753
|
+
}
|
|
754
|
+
if (/^(?:PORT|.*_PORT|.*_TIMEOUT|.*_MS|.*_SECONDS)$/i.test(key)) {
|
|
755
|
+
return "z.coerce.number()";
|
|
756
|
+
}
|
|
757
|
+
if (/^(?:ENABLE|DISABLE|IS|HAS|USE)_|_(?:ENABLED|DISABLED)$/i.test(key)) {
|
|
758
|
+
return "z.coerce.boolean()";
|
|
759
|
+
}
|
|
760
|
+
return "z.string().min(1)";
|
|
761
|
+
}
|
|
762
|
+
function generateZodSchema(result) {
|
|
763
|
+
const keys = /* @__PURE__ */ new Set();
|
|
764
|
+
let hasProcessOrServer = false;
|
|
765
|
+
let hasImportMeta = false;
|
|
766
|
+
for (const [key, refs] of Object.entries(result.usedInCode)) {
|
|
767
|
+
if (BUILTIN_ENV_VARS.has(key)) continue;
|
|
768
|
+
keys.add(key);
|
|
769
|
+
for (const ref of refs) {
|
|
770
|
+
if (ref.source === "import.meta.env") {
|
|
771
|
+
hasImportMeta = true;
|
|
772
|
+
} else {
|
|
773
|
+
hasProcessOrServer = true;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
for (const key of result.unusedInExample) {
|
|
778
|
+
if (!BUILTIN_ENV_VARS.has(key)) {
|
|
779
|
+
keys.add(key);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
const sortedKeys = Array.from(keys).sort();
|
|
783
|
+
const sourceExpr = hasImportMeta && !hasProcessOrServer ? "import.meta.env" : "process.env";
|
|
784
|
+
const lines = [
|
|
785
|
+
"// Auto-generated by env-drift. Customize validators as needed.",
|
|
786
|
+
'import { z } from "zod";',
|
|
787
|
+
"",
|
|
788
|
+
"export const envSchema = z.object({"
|
|
789
|
+
];
|
|
790
|
+
for (const key of sortedKeys) {
|
|
791
|
+
lines.push(` ${key}: ${inferZodRule(key)},`);
|
|
792
|
+
}
|
|
793
|
+
lines.push("});");
|
|
794
|
+
lines.push("");
|
|
795
|
+
lines.push("export type Env = z.infer<typeof envSchema>;");
|
|
796
|
+
lines.push("");
|
|
797
|
+
lines.push(`export const env = envSchema.parse(${sourceExpr});`);
|
|
798
|
+
lines.push("");
|
|
799
|
+
return lines.join("\n");
|
|
800
|
+
}
|
|
801
|
+
function writeZodSchema(outputPath, result) {
|
|
802
|
+
const content = generateZodSchema(result);
|
|
803
|
+
(0, import_node_fs4.mkdirSync)((0, import_node_path5.dirname)(outputPath), { recursive: true });
|
|
804
|
+
(0, import_node_fs4.writeFileSync)(outputPath, content, "utf-8");
|
|
805
|
+
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
806
|
+
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
807
|
+
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
808
|
+
]);
|
|
809
|
+
return { outputPath, count: uniqueKeys.size };
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// src/typegen.ts
|
|
813
|
+
var import_node_fs5 = require("fs");
|
|
814
|
+
var import_node_path6 = require("path");
|
|
411
815
|
function generateEnvTypes(result) {
|
|
412
816
|
const processKeys = /* @__PURE__ */ new Set();
|
|
413
817
|
const importMetaKeys = /* @__PURE__ */ new Set();
|
|
@@ -462,8 +866,8 @@ function generateEnvTypes(result) {
|
|
|
462
866
|
}
|
|
463
867
|
function writeEnvTypes(outputPath, result) {
|
|
464
868
|
const content = generateEnvTypes(result);
|
|
465
|
-
(0,
|
|
466
|
-
(0,
|
|
869
|
+
(0, import_node_fs5.mkdirSync)((0, import_node_path6.dirname)(outputPath), { recursive: true });
|
|
870
|
+
(0, import_node_fs5.writeFileSync)(outputPath, content, "utf-8");
|
|
467
871
|
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
468
872
|
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
469
873
|
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
@@ -472,6 +876,7 @@ function writeEnvTypes(outputPath, result) {
|
|
|
472
876
|
}
|
|
473
877
|
|
|
474
878
|
// src/reporter.ts
|
|
879
|
+
var import_node_path7 = require("path");
|
|
475
880
|
var import_picocolors = __toESM(require("picocolors"), 1);
|
|
476
881
|
function formatRefs(refs) {
|
|
477
882
|
if (!refs || refs.length === 0) return "";
|
|
@@ -481,7 +886,12 @@ function formatRefs(refs) {
|
|
|
481
886
|
}
|
|
482
887
|
function hasBlockingIssues(result, options = {}) {
|
|
483
888
|
const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
|
|
484
|
-
|
|
889
|
+
const baseBlocking = checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
|
|
890
|
+
if (baseBlocking) return true;
|
|
891
|
+
if (options.strict) {
|
|
892
|
+
return result.emptyInEnv.length > 0 || result.unusedInEnv.length > 0 || result.unusedInExample.length > 0 || result.duplicateKeys.env.length > 0 || result.duplicateKeys.example.length > 0;
|
|
893
|
+
}
|
|
894
|
+
return false;
|
|
485
895
|
}
|
|
486
896
|
function formatAuditReport(result, options = {}) {
|
|
487
897
|
const envFile = options.envFile ?? ".env";
|
|
@@ -495,7 +905,7 @@ function formatAuditReport(result, options = {}) {
|
|
|
495
905
|
)}`
|
|
496
906
|
);
|
|
497
907
|
lines.push("");
|
|
498
|
-
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;
|
|
908
|
+
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;
|
|
499
909
|
if (totalIssues === 0) {
|
|
500
910
|
lines.push(import_picocolors.default.green("\u2714 No environment drift detected. Everything is in sync!"));
|
|
501
911
|
if (skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
@@ -517,6 +927,19 @@ function formatAuditReport(result, options = {}) {
|
|
|
517
927
|
}
|
|
518
928
|
lines.push("");
|
|
519
929
|
}
|
|
930
|
+
if (result.exampleSecretLeaks.length > 0) {
|
|
931
|
+
lines.push(
|
|
932
|
+
import_picocolors.default.bold(import_picocolors.default.red(`\u2716 Possible Real Secret in ${exampleFile} (${result.exampleSecretLeaks.length})`))
|
|
933
|
+
);
|
|
934
|
+
for (const item of result.exampleSecretLeaks) {
|
|
935
|
+
lines.push(
|
|
936
|
+
` ${import_picocolors.default.red("\u2022")} ${import_picocolors.default.bold(item.name)} ${import_picocolors.default.dim(
|
|
937
|
+
`(${item.reason}) \u2190 ${item.file}:${item.line}`
|
|
938
|
+
)}`
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
lines.push("");
|
|
942
|
+
}
|
|
520
943
|
if (!skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
521
944
|
lines.push(import_picocolors.default.bold(import_picocolors.default.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
|
|
522
945
|
for (const key of result.missingInEnv) {
|
|
@@ -536,6 +959,13 @@ function formatAuditReport(result, options = {}) {
|
|
|
536
959
|
}
|
|
537
960
|
lines.push("");
|
|
538
961
|
}
|
|
962
|
+
if (result.emptyInEnv.length > 0) {
|
|
963
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.yellow(`\u26A0 Empty Value in ${envFile} (${result.emptyInEnv.length})`)));
|
|
964
|
+
for (const key of result.emptyInEnv) {
|
|
965
|
+
lines.push(` ${import_picocolors.default.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
|
|
966
|
+
}
|
|
967
|
+
lines.push("");
|
|
968
|
+
}
|
|
539
969
|
if (result.unusedInEnv.length > 0) {
|
|
540
970
|
lines.push(import_picocolors.default.bold(import_picocolors.default.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
|
|
541
971
|
for (const key of result.unusedInEnv) {
|
|
@@ -568,6 +998,374 @@ function formatAuditReport(result, options = {}) {
|
|
|
568
998
|
}
|
|
569
999
|
return lines.join("\n");
|
|
570
1000
|
}
|
|
1001
|
+
function escapeGitHubData(value) {
|
|
1002
|
+
return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
1003
|
+
}
|
|
1004
|
+
function escapeGitHubProperty(value) {
|
|
1005
|
+
return escapeGitHubData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
|
|
1006
|
+
}
|
|
1007
|
+
function buildAnnotation(level, title, message, file, line) {
|
|
1008
|
+
const props = [];
|
|
1009
|
+
if (file) props.push(`file=${escapeGitHubProperty(file)}`);
|
|
1010
|
+
if (line !== void 0) props.push(`line=${line}`);
|
|
1011
|
+
props.push(`title=${escapeGitHubProperty(title)}`);
|
|
1012
|
+
return `::${level} ${props.join(",")}::${escapeGitHubData(message)}`;
|
|
1013
|
+
}
|
|
1014
|
+
function formatGitHubAnnotations(result, options = {}) {
|
|
1015
|
+
const envFile = options.envFile ?? ".env";
|
|
1016
|
+
const exampleFile = options.exampleFile ?? ".env.example";
|
|
1017
|
+
const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
|
|
1018
|
+
const lines = [];
|
|
1019
|
+
for (const item of result.secretExposures) {
|
|
1020
|
+
const firstRef = item.references[0];
|
|
1021
|
+
lines.push(
|
|
1022
|
+
buildAnnotation(
|
|
1023
|
+
"error",
|
|
1024
|
+
"Public Secret Exposure",
|
|
1025
|
+
`${item.name} uses client-exposed prefix "${item.prefix}" with sensitive keyword "${item.matchedKeyword}"`,
|
|
1026
|
+
firstRef?.file,
|
|
1027
|
+
firstRef?.line
|
|
1028
|
+
)
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
for (const leak of result.exampleSecretLeaks) {
|
|
1032
|
+
lines.push(
|
|
1033
|
+
buildAnnotation(
|
|
1034
|
+
"error",
|
|
1035
|
+
`Secret Leak in ${exampleFile}`,
|
|
1036
|
+
`${leak.name} appears to contain a real secret (${leak.reason}). Replace it with an empty placeholder.`,
|
|
1037
|
+
leak.file,
|
|
1038
|
+
leak.line
|
|
1039
|
+
)
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
if (!skipMissingInEnv) {
|
|
1043
|
+
for (const key of result.missingInEnv) {
|
|
1044
|
+
const firstRef = result.usedInCode[key]?.[0];
|
|
1045
|
+
lines.push(
|
|
1046
|
+
buildAnnotation(
|
|
1047
|
+
"error",
|
|
1048
|
+
`Missing in ${envFile}`,
|
|
1049
|
+
`Environment variable ${key} is referenced in code but missing in ${envFile}`,
|
|
1050
|
+
firstRef?.file,
|
|
1051
|
+
firstRef?.line
|
|
1052
|
+
)
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
for (const key of result.missingInExample) {
|
|
1057
|
+
const firstRef = result.usedInCode[key]?.[0];
|
|
1058
|
+
lines.push(
|
|
1059
|
+
buildAnnotation(
|
|
1060
|
+
"error",
|
|
1061
|
+
`Missing in ${exampleFile}`,
|
|
1062
|
+
`Environment variable ${key} is referenced in code but missing in ${exampleFile}. Run \`env-drift --sync\` to update.`,
|
|
1063
|
+
firstRef?.file,
|
|
1064
|
+
firstRef?.line
|
|
1065
|
+
)
|
|
1066
|
+
);
|
|
1067
|
+
}
|
|
1068
|
+
for (const key of result.emptyInEnv) {
|
|
1069
|
+
const firstRef = result.usedInCode[key]?.[0];
|
|
1070
|
+
lines.push(
|
|
1071
|
+
buildAnnotation(
|
|
1072
|
+
"warning",
|
|
1073
|
+
`Empty Value in ${envFile}`,
|
|
1074
|
+
`Environment variable ${key} is defined in ${envFile} with an empty value`,
|
|
1075
|
+
firstRef?.file,
|
|
1076
|
+
firstRef?.line
|
|
1077
|
+
)
|
|
1078
|
+
);
|
|
1079
|
+
}
|
|
1080
|
+
for (const key of result.unusedInEnv) {
|
|
1081
|
+
lines.push(
|
|
1082
|
+
buildAnnotation(
|
|
1083
|
+
"warning",
|
|
1084
|
+
`Unused in ${envFile}`,
|
|
1085
|
+
`Environment variable ${key} is defined in ${envFile} but not referenced in code`,
|
|
1086
|
+
envFile
|
|
1087
|
+
)
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
for (const key of result.unusedInExample) {
|
|
1091
|
+
lines.push(
|
|
1092
|
+
buildAnnotation(
|
|
1093
|
+
"warning",
|
|
1094
|
+
`Unused in ${exampleFile}`,
|
|
1095
|
+
`Environment variable ${key} is defined in ${exampleFile} but not referenced in code`,
|
|
1096
|
+
exampleFile
|
|
1097
|
+
)
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
for (const key of result.duplicateKeys.env) {
|
|
1101
|
+
lines.push(
|
|
1102
|
+
buildAnnotation(
|
|
1103
|
+
"warning",
|
|
1104
|
+
`Duplicate Key in ${envFile}`,
|
|
1105
|
+
`Environment variable ${key} is defined multiple times in ${envFile}`,
|
|
1106
|
+
envFile
|
|
1107
|
+
)
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
for (const key of result.duplicateKeys.example) {
|
|
1111
|
+
lines.push(
|
|
1112
|
+
buildAnnotation(
|
|
1113
|
+
"warning",
|
|
1114
|
+
`Duplicate Key in ${exampleFile}`,
|
|
1115
|
+
`Environment variable ${key} is defined multiple times in ${exampleFile}`,
|
|
1116
|
+
exampleFile
|
|
1117
|
+
)
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
return lines.join("\n");
|
|
1121
|
+
}
|
|
1122
|
+
function formatDiffReport(diff) {
|
|
1123
|
+
const lines = [];
|
|
1124
|
+
lines.push("");
|
|
1125
|
+
lines.push(
|
|
1126
|
+
`${import_picocolors.default.bold(import_picocolors.default.cyan("env-drift diff"))} ${import_picocolors.default.dim(`\u2014 ${diff.fileA} \u2194 ${diff.fileB}`)}`
|
|
1127
|
+
);
|
|
1128
|
+
lines.push("");
|
|
1129
|
+
if (!diff.fileAExists) {
|
|
1130
|
+
lines.push(import_picocolors.default.red(`\u2716 File not found: ${diff.fileA}`));
|
|
1131
|
+
}
|
|
1132
|
+
if (!diff.fileBExists) {
|
|
1133
|
+
lines.push(import_picocolors.default.red(`\u2716 File not found: ${diff.fileB}`));
|
|
1134
|
+
}
|
|
1135
|
+
if (!diff.fileAExists || !diff.fileBExists) {
|
|
1136
|
+
lines.push("");
|
|
1137
|
+
return lines.join("\n");
|
|
1138
|
+
}
|
|
1139
|
+
const totalIssues = diff.onlyInA.length + diff.onlyInB.length + diff.emptyInA.length + diff.emptyInB.length;
|
|
1140
|
+
if (totalIssues === 0) {
|
|
1141
|
+
lines.push(
|
|
1142
|
+
import_picocolors.default.green(
|
|
1143
|
+
`\u2714 No drift between ${diff.fileA} and ${diff.fileB} (${diff.inBoth.length} shared key${diff.inBoth.length === 1 ? "" : "s"}).`
|
|
1144
|
+
)
|
|
1145
|
+
);
|
|
1146
|
+
lines.push("");
|
|
1147
|
+
return lines.join("\n");
|
|
1148
|
+
}
|
|
1149
|
+
if (diff.onlyInA.length > 0) {
|
|
1150
|
+
lines.push(
|
|
1151
|
+
import_picocolors.default.bold(import_picocolors.default.red(`\u2716 Only in ${diff.fileA} (missing in ${diff.fileB}) (${diff.onlyInA.length})`))
|
|
1152
|
+
);
|
|
1153
|
+
for (const key of diff.onlyInA) {
|
|
1154
|
+
lines.push(` ${import_picocolors.default.red("\u2022")} ${key}`);
|
|
1155
|
+
}
|
|
1156
|
+
lines.push("");
|
|
1157
|
+
}
|
|
1158
|
+
if (diff.onlyInB.length > 0) {
|
|
1159
|
+
lines.push(
|
|
1160
|
+
import_picocolors.default.bold(import_picocolors.default.red(`\u2716 Only in ${diff.fileB} (missing in ${diff.fileA}) (${diff.onlyInB.length})`))
|
|
1161
|
+
);
|
|
1162
|
+
for (const key of diff.onlyInB) {
|
|
1163
|
+
lines.push(` ${import_picocolors.default.red("\u2022")} ${key}`);
|
|
1164
|
+
}
|
|
1165
|
+
lines.push("");
|
|
1166
|
+
}
|
|
1167
|
+
if (diff.emptyInA.length > 0) {
|
|
1168
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.yellow(`\u26A0 Empty in ${diff.fileA} (${diff.emptyInA.length})`)));
|
|
1169
|
+
for (const key of diff.emptyInA) {
|
|
1170
|
+
lines.push(` ${import_picocolors.default.yellow("\u2022")} ${key}`);
|
|
1171
|
+
}
|
|
1172
|
+
lines.push("");
|
|
1173
|
+
}
|
|
1174
|
+
if (diff.emptyInB.length > 0) {
|
|
1175
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.yellow(`\u26A0 Empty in ${diff.fileB} (${diff.emptyInB.length})`)));
|
|
1176
|
+
for (const key of diff.emptyInB) {
|
|
1177
|
+
lines.push(` ${import_picocolors.default.yellow("\u2022")} ${key}`);
|
|
1178
|
+
}
|
|
1179
|
+
lines.push("");
|
|
1180
|
+
}
|
|
1181
|
+
lines.push(import_picocolors.default.dim(`Shared keys in both files: ${diff.inBoth.length}`));
|
|
1182
|
+
lines.push("");
|
|
1183
|
+
return lines.join("\n");
|
|
1184
|
+
}
|
|
1185
|
+
function formatWorkspaceReport(wsResult, options = {}) {
|
|
1186
|
+
const lines = [];
|
|
1187
|
+
lines.push("");
|
|
1188
|
+
lines.push(
|
|
1189
|
+
`${import_picocolors.default.bold(import_picocolors.default.cyan("env-drift workspaces"))} ${import_picocolors.default.dim(
|
|
1190
|
+
`\u2014 audited ${wsResult.workspaces.length} workspace${wsResult.workspaces.length === 1 ? "" : "s"}`
|
|
1191
|
+
)}`
|
|
1192
|
+
);
|
|
1193
|
+
if (wsResult.workspaces.length === 0) {
|
|
1194
|
+
lines.push("");
|
|
1195
|
+
lines.push(import_picocolors.default.yellow("\u26A0 No workspaces found in package.json or pnpm-workspace.yaml."));
|
|
1196
|
+
lines.push("");
|
|
1197
|
+
return lines.join("\n");
|
|
1198
|
+
}
|
|
1199
|
+
for (const ws of wsResult.workspaces) {
|
|
1200
|
+
const rel = (0, import_node_path7.relative)(wsResult.rootDir, ws.path).replace(/\\/g, "/");
|
|
1201
|
+
lines.push("");
|
|
1202
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.white(`\u25B8 ${ws.name}`)) + import_picocolors.default.dim(` (${rel})`));
|
|
1203
|
+
lines.push(formatAuditReport(ws.result, options).trimEnd());
|
|
1204
|
+
}
|
|
1205
|
+
lines.push("");
|
|
1206
|
+
return lines.join("\n");
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
// src/workspaces.ts
|
|
1210
|
+
var import_node_fs6 = require("fs");
|
|
1211
|
+
var import_node_path8 = require("path");
|
|
1212
|
+
function readWorkspacePatterns(rootDir) {
|
|
1213
|
+
const pkgPath = (0, import_node_path8.resolve)(rootDir, "package.json");
|
|
1214
|
+
if ((0, import_node_fs6.existsSync)(pkgPath)) {
|
|
1215
|
+
try {
|
|
1216
|
+
const parsed = JSON.parse((0, import_node_fs6.readFileSync)(pkgPath, "utf-8"));
|
|
1217
|
+
if (Array.isArray(parsed.workspaces)) {
|
|
1218
|
+
return parsed.workspaces.filter((p) => typeof p === "string");
|
|
1219
|
+
}
|
|
1220
|
+
if (parsed.workspaces && typeof parsed.workspaces === "object" && Array.isArray(parsed.workspaces.packages)) {
|
|
1221
|
+
return parsed.workspaces.packages.filter((p) => typeof p === "string");
|
|
1222
|
+
}
|
|
1223
|
+
} catch {
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
const pnpmPath = (0, import_node_path8.resolve)(rootDir, "pnpm-workspace.yaml");
|
|
1227
|
+
if ((0, import_node_fs6.existsSync)(pnpmPath)) {
|
|
1228
|
+
const content = (0, import_node_fs6.readFileSync)(pnpmPath, "utf-8");
|
|
1229
|
+
const patterns = [];
|
|
1230
|
+
let inPackages = false;
|
|
1231
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
1232
|
+
const line = rawLine.trim();
|
|
1233
|
+
if (!line || line.startsWith("#")) continue;
|
|
1234
|
+
if (/^packages\s*:/.test(line)) {
|
|
1235
|
+
inPackages = true;
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
if (inPackages) {
|
|
1239
|
+
if (line.startsWith("-")) {
|
|
1240
|
+
const item = line.slice(1).trim().replace(/^["']|["']$/g, "");
|
|
1241
|
+
if (item) patterns.push(item);
|
|
1242
|
+
} else if (/^[A-Za-z0-9_-]+\s*:/.test(line)) {
|
|
1243
|
+
inPackages = false;
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
if (patterns.length > 0) return patterns;
|
|
1248
|
+
}
|
|
1249
|
+
return [];
|
|
1250
|
+
}
|
|
1251
|
+
function expandPattern(rootDir, pattern) {
|
|
1252
|
+
const cleaned = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
1253
|
+
const segments = cleaned.split("/").filter(Boolean);
|
|
1254
|
+
let currentDirs = [rootDir];
|
|
1255
|
+
for (const seg of segments) {
|
|
1256
|
+
const nextDirs = [];
|
|
1257
|
+
if (seg === "*" || seg === "**") {
|
|
1258
|
+
for (const dir of currentDirs) {
|
|
1259
|
+
if (!(0, import_node_fs6.existsSync)(dir)) continue;
|
|
1260
|
+
for (const entry of (0, import_node_fs6.readdirSync)(dir, { withFileTypes: true })) {
|
|
1261
|
+
if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
|
|
1262
|
+
nextDirs.push((0, import_node_path8.join)(dir, entry.name));
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
} else if (seg.includes("*")) {
|
|
1267
|
+
const regex = new RegExp(
|
|
1268
|
+
"^" + seg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$"
|
|
1269
|
+
);
|
|
1270
|
+
for (const dir of currentDirs) {
|
|
1271
|
+
if (!(0, import_node_fs6.existsSync)(dir)) continue;
|
|
1272
|
+
for (const entry of (0, import_node_fs6.readdirSync)(dir, { withFileTypes: true })) {
|
|
1273
|
+
if (entry.isDirectory() && regex.test(entry.name)) {
|
|
1274
|
+
nextDirs.push((0, import_node_path8.join)(dir, entry.name));
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
} else {
|
|
1279
|
+
for (const dir of currentDirs) {
|
|
1280
|
+
const candidate = (0, import_node_path8.join)(dir, seg);
|
|
1281
|
+
if ((0, import_node_fs6.existsSync)(candidate) && (0, import_node_fs6.statSync)(candidate).isDirectory()) {
|
|
1282
|
+
nextDirs.push(candidate);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
currentDirs = nextDirs;
|
|
1287
|
+
}
|
|
1288
|
+
return currentDirs;
|
|
1289
|
+
}
|
|
1290
|
+
function discoverWorkspaces(rootDir) {
|
|
1291
|
+
const resolvedRoot = (0, import_node_path8.resolve)(rootDir);
|
|
1292
|
+
const patterns = readWorkspacePatterns(resolvedRoot);
|
|
1293
|
+
if (patterns.length === 0) return [];
|
|
1294
|
+
const included = /* @__PURE__ */ new Set();
|
|
1295
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
1296
|
+
for (const pattern of patterns) {
|
|
1297
|
+
if (pattern.startsWith("!")) {
|
|
1298
|
+
for (const dir of expandPattern(resolvedRoot, pattern.slice(1))) {
|
|
1299
|
+
excluded.add((0, import_node_path8.resolve)(dir));
|
|
1300
|
+
}
|
|
1301
|
+
} else {
|
|
1302
|
+
for (const dir of expandPattern(resolvedRoot, pattern)) {
|
|
1303
|
+
included.add((0, import_node_path8.resolve)(dir));
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
const results = [];
|
|
1308
|
+
for (const dir of included) {
|
|
1309
|
+
if (excluded.has(dir)) continue;
|
|
1310
|
+
const relPath = (0, import_node_path8.relative)(resolvedRoot, dir).replace(/\\/g, "/");
|
|
1311
|
+
let name = relPath;
|
|
1312
|
+
const pkgPath = (0, import_node_path8.join)(dir, "package.json");
|
|
1313
|
+
if ((0, import_node_fs6.existsSync)(pkgPath)) {
|
|
1314
|
+
try {
|
|
1315
|
+
const pkg = JSON.parse((0, import_node_fs6.readFileSync)(pkgPath, "utf-8"));
|
|
1316
|
+
if (typeof pkg.name === "string" && pkg.name.trim()) {
|
|
1317
|
+
name = pkg.name.trim();
|
|
1318
|
+
}
|
|
1319
|
+
} catch {
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
results.push({ name, path: dir });
|
|
1323
|
+
}
|
|
1324
|
+
results.sort((a, b) => a.path.localeCompare(b.path));
|
|
1325
|
+
return results;
|
|
1326
|
+
}
|
|
1327
|
+
function auditWorkspaces(rootDir, options = {}) {
|
|
1328
|
+
const resolvedRoot = (0, import_node_path8.resolve)(rootDir);
|
|
1329
|
+
const discovered = discoverWorkspaces(resolvedRoot);
|
|
1330
|
+
const workspaces = [];
|
|
1331
|
+
for (const ws of discovered) {
|
|
1332
|
+
const wsConfig = loadConfig(ws.path);
|
|
1333
|
+
const mergedIgnore = [
|
|
1334
|
+
...options.ignore ?? [],
|
|
1335
|
+
...wsConfig.ignore ?? []
|
|
1336
|
+
];
|
|
1337
|
+
const mergedIgnoreDirs = [
|
|
1338
|
+
...options.ignoreDirs ?? [],
|
|
1339
|
+
...wsConfig.ignoreDirs ?? []
|
|
1340
|
+
];
|
|
1341
|
+
const mergedPrefixes = [
|
|
1342
|
+
...options.publicPrefixes ?? [],
|
|
1343
|
+
...wsConfig.publicPrefixes ?? []
|
|
1344
|
+
];
|
|
1345
|
+
const mergedKeywords = [
|
|
1346
|
+
...options.sensitiveKeywords ?? [],
|
|
1347
|
+
...wsConfig.sensitiveKeywords ?? []
|
|
1348
|
+
];
|
|
1349
|
+
const result = auditEnv({
|
|
1350
|
+
rootDir: ws.path,
|
|
1351
|
+
envFile: options.envFile ?? wsConfig.envFile,
|
|
1352
|
+
exampleFile: options.exampleFile ?? wsConfig.exampleFile,
|
|
1353
|
+
ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
|
|
1354
|
+
ignoreDirs: mergedIgnoreDirs.length > 0 ? mergedIgnoreDirs : void 0,
|
|
1355
|
+
publicPrefixes: mergedPrefixes.length > 0 ? mergedPrefixes : void 0,
|
|
1356
|
+
sensitiveKeywords: mergedKeywords.length > 0 ? mergedKeywords : void 0
|
|
1357
|
+
});
|
|
1358
|
+
workspaces.push({
|
|
1359
|
+
name: ws.name,
|
|
1360
|
+
path: ws.path,
|
|
1361
|
+
result
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
return {
|
|
1365
|
+
rootDir: resolvedRoot,
|
|
1366
|
+
workspaces
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
571
1369
|
// Annotate the CommonJS export names for ESM import in node:
|
|
572
1370
|
0 && (module.exports = {
|
|
573
1371
|
BUILTIN_ENV_VARS,
|
|
@@ -576,14 +1374,26 @@ function formatAuditReport(result, options = {}) {
|
|
|
576
1374
|
PUBLIC_ENV_PREFIXES,
|
|
577
1375
|
SENSITIVE_KEYWORDS,
|
|
578
1376
|
auditEnv,
|
|
1377
|
+
auditWorkspaces,
|
|
1378
|
+
detectExampleSecretLeak,
|
|
579
1379
|
detectSecretExposure,
|
|
1380
|
+
diffEnvFiles,
|
|
1381
|
+
discoverWorkspaces,
|
|
580
1382
|
extractEnvReferences,
|
|
581
1383
|
formatAuditReport,
|
|
1384
|
+
formatDiffReport,
|
|
1385
|
+
formatGitHubAnnotations,
|
|
1386
|
+
formatWorkspaceReport,
|
|
582
1387
|
generateEnvTypes,
|
|
1388
|
+
generateZodSchema,
|
|
583
1389
|
hasBlockingIssues,
|
|
1390
|
+
hasDiffIssues,
|
|
1391
|
+
inferZodRule,
|
|
1392
|
+
loadConfig,
|
|
584
1393
|
parseEnvContent,
|
|
585
1394
|
parseEnvFile,
|
|
586
1395
|
scanFiles,
|
|
587
1396
|
syncEnvExample,
|
|
588
|
-
writeEnvTypes
|
|
1397
|
+
writeEnvTypes,
|
|
1398
|
+
writeZodSchema
|
|
589
1399
|
});
|