@subramanyaks/env-drift 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +137 -2
- package/dist/cli.js +720 -0
- package/dist/index.cjs +589 -0
- package/dist/index.d.cts +126 -0
- package/dist/index.d.ts +126 -0
- package/dist/index.js +537 -0
- package/package.json +67 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
BUILTIN_ENV_VARS: () => BUILTIN_ENV_VARS,
|
|
34
|
+
DEFAULT_EXTENSIONS: () => DEFAULT_EXTENSIONS,
|
|
35
|
+
DEFAULT_IGNORE_DIRS: () => DEFAULT_IGNORE_DIRS,
|
|
36
|
+
PUBLIC_ENV_PREFIXES: () => PUBLIC_ENV_PREFIXES,
|
|
37
|
+
SENSITIVE_KEYWORDS: () => SENSITIVE_KEYWORDS,
|
|
38
|
+
auditEnv: () => auditEnv,
|
|
39
|
+
detectSecretExposure: () => detectSecretExposure,
|
|
40
|
+
extractEnvReferences: () => extractEnvReferences,
|
|
41
|
+
formatAuditReport: () => formatAuditReport,
|
|
42
|
+
generateEnvTypes: () => generateEnvTypes,
|
|
43
|
+
hasBlockingIssues: () => hasBlockingIssues,
|
|
44
|
+
parseEnvContent: () => parseEnvContent,
|
|
45
|
+
parseEnvFile: () => parseEnvFile,
|
|
46
|
+
scanFiles: () => scanFiles,
|
|
47
|
+
syncEnvExample: () => syncEnvExample,
|
|
48
|
+
writeEnvTypes: () => writeEnvTypes
|
|
49
|
+
});
|
|
50
|
+
module.exports = __toCommonJS(src_exports);
|
|
51
|
+
|
|
52
|
+
// src/analyzer.ts
|
|
53
|
+
var import_node_path2 = require("path");
|
|
54
|
+
|
|
55
|
+
// src/envParser.ts
|
|
56
|
+
var import_node_fs = require("fs");
|
|
57
|
+
var ENV_LINE_REGEX = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
|
58
|
+
function parseValue(raw) {
|
|
59
|
+
const trimmed = raw.trim();
|
|
60
|
+
if (!trimmed) return "";
|
|
61
|
+
const quote = trimmed[0];
|
|
62
|
+
if (quote === '"') {
|
|
63
|
+
let result = "";
|
|
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;
|
|
80
|
+
}
|
|
81
|
+
if (quote === "'") {
|
|
82
|
+
const closingIdx = trimmed.indexOf("'", 1);
|
|
83
|
+
if (closingIdx !== -1) {
|
|
84
|
+
return trimmed.slice(1, closingIdx);
|
|
85
|
+
}
|
|
86
|
+
return trimmed.slice(1);
|
|
87
|
+
}
|
|
88
|
+
const commentIdx = trimmed.indexOf(" #");
|
|
89
|
+
if (commentIdx !== -1) {
|
|
90
|
+
return trimmed.slice(0, commentIdx).trim();
|
|
91
|
+
}
|
|
92
|
+
return trimmed;
|
|
93
|
+
}
|
|
94
|
+
function parseEnvContent(content) {
|
|
95
|
+
const keys = [];
|
|
96
|
+
const seen = /* @__PURE__ */ new Set();
|
|
97
|
+
const duplicateSet = /* @__PURE__ */ new Set();
|
|
98
|
+
const values = {};
|
|
99
|
+
const lines = content.split(/\r?\n/);
|
|
100
|
+
for (const rawLine of lines) {
|
|
101
|
+
const line = rawLine.trim();
|
|
102
|
+
if (!line || line.startsWith("#")) continue;
|
|
103
|
+
const match = ENV_LINE_REGEX.exec(line);
|
|
104
|
+
if (!match) continue;
|
|
105
|
+
const key = match[1];
|
|
106
|
+
const rawValue = match[2] ?? "";
|
|
107
|
+
if (!key) continue;
|
|
108
|
+
if (seen.has(key)) {
|
|
109
|
+
duplicateSet.add(key);
|
|
110
|
+
} else {
|
|
111
|
+
seen.add(key);
|
|
112
|
+
keys.push(key);
|
|
113
|
+
}
|
|
114
|
+
values[key] = parseValue(rawValue);
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
keys,
|
|
118
|
+
values,
|
|
119
|
+
duplicates: Array.from(duplicateSet)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function parseEnvFile(filePath) {
|
|
123
|
+
if (!(0, import_node_fs.existsSync)(filePath)) {
|
|
124
|
+
return {
|
|
125
|
+
filePath,
|
|
126
|
+
exists: false,
|
|
127
|
+
keys: [],
|
|
128
|
+
values: {},
|
|
129
|
+
duplicates: []
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
const content = (0, import_node_fs.readFileSync)(filePath, "utf-8");
|
|
133
|
+
const { keys, values, duplicates } = parseEnvContent(content);
|
|
134
|
+
return {
|
|
135
|
+
filePath,
|
|
136
|
+
exists: true,
|
|
137
|
+
keys,
|
|
138
|
+
values,
|
|
139
|
+
duplicates
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function syncEnvExample(examplePath, missingKeys) {
|
|
143
|
+
const uniqueKeys = Array.from(new Set(missingKeys)).sort();
|
|
144
|
+
if (uniqueKeys.length === 0) {
|
|
145
|
+
return { added: [], created: false };
|
|
146
|
+
}
|
|
147
|
+
const created = !(0, import_node_fs.existsSync)(examplePath);
|
|
148
|
+
const existingContent = created ? "" : (0, import_node_fs.readFileSync)(examplePath, "utf-8");
|
|
149
|
+
const existingKeys = new Set(parseEnvContent(existingContent).keys);
|
|
150
|
+
const toAdd = uniqueKeys.filter((k) => !existingKeys.has(k));
|
|
151
|
+
if (toAdd.length === 0) {
|
|
152
|
+
return { added: [], created: false };
|
|
153
|
+
}
|
|
154
|
+
const linesBlock = toAdd.map((k) => `${k}=`).join("\n") + "\n";
|
|
155
|
+
let nextContent;
|
|
156
|
+
if (created || existingContent.trim() === "") {
|
|
157
|
+
nextContent = linesBlock;
|
|
158
|
+
} else {
|
|
159
|
+
const separator = existingContent.endsWith("\n") ? "" : "\n";
|
|
160
|
+
nextContent = `${existingContent}${separator}${linesBlock}`;
|
|
161
|
+
}
|
|
162
|
+
(0, import_node_fs.writeFileSync)(examplePath, nextContent, "utf-8");
|
|
163
|
+
return { added: toAdd, created };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/scanner.ts
|
|
167
|
+
var import_node_fs2 = require("fs");
|
|
168
|
+
var import_node_path = require("path");
|
|
169
|
+
var DEFAULT_IGNORE_DIRS = /* @__PURE__ */ new Set([
|
|
170
|
+
"node_modules",
|
|
171
|
+
".git",
|
|
172
|
+
"dist",
|
|
173
|
+
"build",
|
|
174
|
+
".next",
|
|
175
|
+
".nuxt",
|
|
176
|
+
".svelte-kit",
|
|
177
|
+
".vercel",
|
|
178
|
+
".turbo",
|
|
179
|
+
"coverage",
|
|
180
|
+
"out",
|
|
181
|
+
".cache"
|
|
182
|
+
]);
|
|
183
|
+
var DEFAULT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
184
|
+
".js",
|
|
185
|
+
".jsx",
|
|
186
|
+
".ts",
|
|
187
|
+
".tsx",
|
|
188
|
+
".mjs",
|
|
189
|
+
".cjs",
|
|
190
|
+
".mts",
|
|
191
|
+
".cts",
|
|
192
|
+
".vue",
|
|
193
|
+
".svelte",
|
|
194
|
+
".astro"
|
|
195
|
+
]);
|
|
196
|
+
function stripCommentsPreservingLines(source) {
|
|
197
|
+
const tokenRegex = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g;
|
|
198
|
+
return source.replace(tokenRegex, (match, stringLiteral) => {
|
|
199
|
+
if (stringLiteral) return match;
|
|
200
|
+
return match.replace(/[^\r\n]/g, " ");
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
function getLineNumber(source, index) {
|
|
204
|
+
let line = 1;
|
|
205
|
+
for (let i = 0; i < index; i++) {
|
|
206
|
+
if (source.charCodeAt(i) === 10) line++;
|
|
207
|
+
}
|
|
208
|
+
return line;
|
|
209
|
+
}
|
|
210
|
+
function extractEnvReferences(content, filePath) {
|
|
211
|
+
const cleaned = stripCommentsPreservingLines(content);
|
|
212
|
+
const refs = [];
|
|
213
|
+
const normalizedFile = filePath.replace(/\\/g, "/");
|
|
214
|
+
const dotRegex = /\b(process\.env|import\.meta\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
|
|
215
|
+
for (const match of cleaned.matchAll(dotRegex)) {
|
|
216
|
+
const source = match[1];
|
|
217
|
+
const name = match[2];
|
|
218
|
+
if (!name || match.index === void 0) continue;
|
|
219
|
+
refs.push({
|
|
220
|
+
name,
|
|
221
|
+
file: normalizedFile,
|
|
222
|
+
line: getLineNumber(cleaned, match.index),
|
|
223
|
+
source
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
const bracketRegex = /\b(process\.env|import\.meta\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
|
|
227
|
+
for (const match of cleaned.matchAll(bracketRegex)) {
|
|
228
|
+
const source = match[1];
|
|
229
|
+
const name = match[2];
|
|
230
|
+
if (!name || match.index === void 0) continue;
|
|
231
|
+
refs.push({
|
|
232
|
+
name,
|
|
233
|
+
file: normalizedFile,
|
|
234
|
+
line: getLineNumber(cleaned, match.index),
|
|
235
|
+
source
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
|
|
239
|
+
for (const match of cleaned.matchAll(destructureRegex)) {
|
|
240
|
+
const body = match[1];
|
|
241
|
+
const source = match[2];
|
|
242
|
+
if (!body || match.index === void 0) continue;
|
|
243
|
+
const bodyStart = match.index + 1;
|
|
244
|
+
let offset = 0;
|
|
245
|
+
for (const part of body.split(",")) {
|
|
246
|
+
const partIdx = body.indexOf(part, offset);
|
|
247
|
+
offset = partIdx + part.length + 1;
|
|
248
|
+
const trimmed = part.trim();
|
|
249
|
+
if (!trimmed || trimmed.startsWith("...")) continue;
|
|
250
|
+
const keyMatch = /^([A-Za-z_][A-Za-z0-9_]*)/.exec(trimmed);
|
|
251
|
+
const name = keyMatch?.[1];
|
|
252
|
+
if (!name) continue;
|
|
253
|
+
const leadingWs = part.indexOf(name);
|
|
254
|
+
const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
|
|
255
|
+
refs.push({
|
|
256
|
+
name,
|
|
257
|
+
file: normalizedFile,
|
|
258
|
+
line: getLineNumber(cleaned, absoluteIdx),
|
|
259
|
+
source
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
refs.sort((a, b) => a.line - b.line);
|
|
264
|
+
return refs;
|
|
265
|
+
}
|
|
266
|
+
function scanFiles(rootDir, options = {}) {
|
|
267
|
+
const ignoreDirs = options.ignoreDirs ? new Set(options.ignoreDirs) : DEFAULT_IGNORE_DIRS;
|
|
268
|
+
const extensions = options.extensions ? new Set(options.extensions) : DEFAULT_EXTENSIONS;
|
|
269
|
+
let scannedFiles = 0;
|
|
270
|
+
const references = [];
|
|
271
|
+
function walk(currentDir) {
|
|
272
|
+
const entries = (0, import_node_fs2.readdirSync)(currentDir, { withFileTypes: true });
|
|
273
|
+
for (const entry of entries) {
|
|
274
|
+
const fullPath = (0, import_node_path.join)(currentDir, entry.name);
|
|
275
|
+
if (entry.isDirectory()) {
|
|
276
|
+
if (ignoreDirs.has(entry.name)) continue;
|
|
277
|
+
walk(fullPath);
|
|
278
|
+
} else if (entry.isFile()) {
|
|
279
|
+
const ext = (0, import_node_path.extname)(entry.name).toLowerCase();
|
|
280
|
+
if (!extensions.has(ext)) continue;
|
|
281
|
+
const size = (0, import_node_fs2.statSync)(fullPath).size;
|
|
282
|
+
if (size > 2 * 1024 * 1024) continue;
|
|
283
|
+
scannedFiles++;
|
|
284
|
+
const content = (0, import_node_fs2.readFileSync)(fullPath, "utf-8");
|
|
285
|
+
const relPath = (0, import_node_path.relative)(rootDir, fullPath);
|
|
286
|
+
const fileRefs = extractEnvReferences(content, relPath);
|
|
287
|
+
references.push(...fileRefs);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
walk(rootDir);
|
|
292
|
+
return { scannedFiles, references };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// src/analyzer.ts
|
|
296
|
+
var BUILTIN_ENV_VARS = /* @__PURE__ */ new Set([
|
|
297
|
+
"NODE_ENV",
|
|
298
|
+
"CI",
|
|
299
|
+
"MODE",
|
|
300
|
+
"DEV",
|
|
301
|
+
"PROD",
|
|
302
|
+
"SSR",
|
|
303
|
+
"BASE_URL"
|
|
304
|
+
]);
|
|
305
|
+
var PUBLIC_ENV_PREFIXES = [
|
|
306
|
+
"NEXT_PUBLIC_",
|
|
307
|
+
"VITE_",
|
|
308
|
+
"REACT_APP_",
|
|
309
|
+
"NUXT_PUBLIC_",
|
|
310
|
+
"PUBLIC_",
|
|
311
|
+
"EXPO_PUBLIC_",
|
|
312
|
+
"GATSBY_"
|
|
313
|
+
];
|
|
314
|
+
var SENSITIVE_KEYWORDS = [
|
|
315
|
+
"SECRET",
|
|
316
|
+
"PASSWORD",
|
|
317
|
+
"PASSWD",
|
|
318
|
+
"PRIVATE_KEY",
|
|
319
|
+
"PRIVATE",
|
|
320
|
+
"DATABASE_URL",
|
|
321
|
+
"DB_URL",
|
|
322
|
+
"DB_PASS",
|
|
323
|
+
"JWT_SECRET",
|
|
324
|
+
"AUTH_TOKEN",
|
|
325
|
+
"ACCESS_KEY",
|
|
326
|
+
"API_SECRET",
|
|
327
|
+
"SERVICE_ROLE",
|
|
328
|
+
"CREDENTIALS"
|
|
329
|
+
];
|
|
330
|
+
function detectSecretExposure(name) {
|
|
331
|
+
const upper = name.toUpperCase();
|
|
332
|
+
const prefix = PUBLIC_ENV_PREFIXES.find((p) => upper.startsWith(p));
|
|
333
|
+
if (!prefix) return null;
|
|
334
|
+
const rest = upper.slice(prefix.length);
|
|
335
|
+
const matchedKeyword = SENSITIVE_KEYWORDS.find((kw) => rest.includes(kw));
|
|
336
|
+
if (!matchedKeyword) return null;
|
|
337
|
+
return { prefix, matchedKeyword };
|
|
338
|
+
}
|
|
339
|
+
function auditEnv(options = {}) {
|
|
340
|
+
const rootDir = (0, import_node_path2.resolve)(options.rootDir ?? process.cwd());
|
|
341
|
+
const envFileName = options.envFile ?? ".env";
|
|
342
|
+
const exampleFileName = options.exampleFile ?? ".env.example";
|
|
343
|
+
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
344
|
+
const { scannedFiles, references } = scanFiles(rootDir);
|
|
345
|
+
const usedInCode = {};
|
|
346
|
+
for (const ref of references) {
|
|
347
|
+
if (!usedInCode[ref.name]) {
|
|
348
|
+
usedInCode[ref.name] = [];
|
|
349
|
+
}
|
|
350
|
+
usedInCode[ref.name].push(ref);
|
|
351
|
+
}
|
|
352
|
+
const parsedEnv = parseEnvFile((0, import_node_path2.resolve)(rootDir, envFileName));
|
|
353
|
+
const parsedExample = parseEnvFile((0, import_node_path2.resolve)(rootDir, exampleFileName));
|
|
354
|
+
let envFileExists = parsedEnv.exists;
|
|
355
|
+
const localEnvKeys = new Set(parsedEnv.keys);
|
|
356
|
+
if (!options.envFile) {
|
|
357
|
+
const parsedLocal = parseEnvFile((0, import_node_path2.resolve)(rootDir, ".env.local"));
|
|
358
|
+
if (parsedLocal.exists) {
|
|
359
|
+
envFileExists = true;
|
|
360
|
+
}
|
|
361
|
+
for (const key of parsedLocal.keys) {
|
|
362
|
+
localEnvKeys.add(key);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const exampleKeys = new Set(parsedExample.keys);
|
|
366
|
+
const codeKeys = Object.keys(usedInCode);
|
|
367
|
+
const codeKeySet = new Set(codeKeys);
|
|
368
|
+
const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
|
|
369
|
+
const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
|
|
370
|
+
const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
371
|
+
const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
|
|
372
|
+
const allKnownKeys = /* @__PURE__ */ new Set([
|
|
373
|
+
...codeKeys,
|
|
374
|
+
...localEnvKeys,
|
|
375
|
+
...exampleKeys
|
|
376
|
+
]);
|
|
377
|
+
const secretExposures = [];
|
|
378
|
+
for (const key of Array.from(allKnownKeys).sort()) {
|
|
379
|
+
if (ignoreSet.has(key)) continue;
|
|
380
|
+
const hit = detectSecretExposure(key);
|
|
381
|
+
if (hit) {
|
|
382
|
+
secretExposures.push({
|
|
383
|
+
name: key,
|
|
384
|
+
prefix: hit.prefix,
|
|
385
|
+
matchedKeyword: hit.matchedKeyword,
|
|
386
|
+
references: usedInCode[key] ?? []
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return {
|
|
391
|
+
rootDir,
|
|
392
|
+
scannedFiles,
|
|
393
|
+
envFileExists,
|
|
394
|
+
exampleFileExists: parsedExample.exists,
|
|
395
|
+
usedInCode,
|
|
396
|
+
missingInEnv,
|
|
397
|
+
missingInExample,
|
|
398
|
+
unusedInEnv,
|
|
399
|
+
unusedInExample,
|
|
400
|
+
secretExposures,
|
|
401
|
+
duplicateKeys: {
|
|
402
|
+
env: parsedEnv.duplicates,
|
|
403
|
+
example: parsedExample.duplicates
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/typegen.ts
|
|
409
|
+
var import_node_fs3 = require("fs");
|
|
410
|
+
var import_node_path3 = require("path");
|
|
411
|
+
function generateEnvTypes(result) {
|
|
412
|
+
const processKeys = /* @__PURE__ */ new Set();
|
|
413
|
+
const importMetaKeys = /* @__PURE__ */ new Set();
|
|
414
|
+
for (const [key, refs] of Object.entries(result.usedInCode)) {
|
|
415
|
+
if (BUILTIN_ENV_VARS.has(key)) continue;
|
|
416
|
+
for (const ref of refs) {
|
|
417
|
+
if (ref.source === "import.meta.env") {
|
|
418
|
+
importMetaKeys.add(key);
|
|
419
|
+
} else {
|
|
420
|
+
processKeys.add(key);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
for (const key of result.unusedInExample) {
|
|
425
|
+
if (!BUILTIN_ENV_VARS.has(key) && !importMetaKeys.has(key)) {
|
|
426
|
+
processKeys.add(key);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const lines = [
|
|
430
|
+
"// Auto-generated by env-drift. Do not edit manually.",
|
|
431
|
+
""
|
|
432
|
+
];
|
|
433
|
+
const sortedProcess = Array.from(processKeys).sort();
|
|
434
|
+
if (sortedProcess.length > 0) {
|
|
435
|
+
lines.push("declare namespace NodeJS {");
|
|
436
|
+
lines.push(" interface ProcessEnv {");
|
|
437
|
+
for (const key of sortedProcess) {
|
|
438
|
+
lines.push(` ${key}: string;`);
|
|
439
|
+
}
|
|
440
|
+
lines.push(" }");
|
|
441
|
+
lines.push("}");
|
|
442
|
+
lines.push("");
|
|
443
|
+
}
|
|
444
|
+
const sortedMeta = Array.from(importMetaKeys).sort();
|
|
445
|
+
if (sortedMeta.length > 0) {
|
|
446
|
+
lines.push("interface ImportMetaEnv {");
|
|
447
|
+
for (const key of sortedMeta) {
|
|
448
|
+
lines.push(` readonly ${key}: string;`);
|
|
449
|
+
}
|
|
450
|
+
lines.push("}");
|
|
451
|
+
lines.push("");
|
|
452
|
+
lines.push("interface ImportMeta {");
|
|
453
|
+
lines.push(" readonly env: ImportMetaEnv;");
|
|
454
|
+
lines.push("}");
|
|
455
|
+
lines.push("");
|
|
456
|
+
}
|
|
457
|
+
if (sortedProcess.length === 0 && sortedMeta.length === 0) {
|
|
458
|
+
lines.push("// No environment variables detected.");
|
|
459
|
+
lines.push("");
|
|
460
|
+
}
|
|
461
|
+
return lines.join("\n");
|
|
462
|
+
}
|
|
463
|
+
function writeEnvTypes(outputPath, result) {
|
|
464
|
+
const content = generateEnvTypes(result);
|
|
465
|
+
(0, import_node_fs3.mkdirSync)((0, import_node_path3.dirname)(outputPath), { recursive: true });
|
|
466
|
+
(0, import_node_fs3.writeFileSync)(outputPath, content, "utf-8");
|
|
467
|
+
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
468
|
+
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
469
|
+
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
470
|
+
]);
|
|
471
|
+
return { outputPath, count: uniqueKeys.size };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// src/reporter.ts
|
|
475
|
+
var import_picocolors = __toESM(require("picocolors"), 1);
|
|
476
|
+
function formatRefs(refs) {
|
|
477
|
+
if (!refs || refs.length === 0) return "";
|
|
478
|
+
const shown = refs.slice(0, 2).map((r) => `${r.file}:${r.line}`);
|
|
479
|
+
const extra = refs.length > 2 ? ` (+${refs.length - 2} more)` : "";
|
|
480
|
+
return import_picocolors.default.dim(` \u2190 ${shown.join(", ")}${extra}`);
|
|
481
|
+
}
|
|
482
|
+
function hasBlockingIssues(result, options = {}) {
|
|
483
|
+
const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
|
|
484
|
+
return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0;
|
|
485
|
+
}
|
|
486
|
+
function formatAuditReport(result, options = {}) {
|
|
487
|
+
const envFile = options.envFile ?? ".env";
|
|
488
|
+
const exampleFile = options.exampleFile ?? ".env.example";
|
|
489
|
+
const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
|
|
490
|
+
const lines = [];
|
|
491
|
+
lines.push("");
|
|
492
|
+
lines.push(
|
|
493
|
+
`${import_picocolors.default.bold(import_picocolors.default.cyan("env-drift"))} ${import_picocolors.default.dim(
|
|
494
|
+
`\u2014 scanned ${result.scannedFiles} file${result.scannedFiles === 1 ? "" : "s"}`
|
|
495
|
+
)}`
|
|
496
|
+
);
|
|
497
|
+
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;
|
|
499
|
+
if (totalIssues === 0) {
|
|
500
|
+
lines.push(import_picocolors.default.green("\u2714 No environment drift detected. Everything is in sync!"));
|
|
501
|
+
if (skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
502
|
+
lines.push(
|
|
503
|
+
import_picocolors.default.dim(` (No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode)`)
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
lines.push("");
|
|
507
|
+
return lines.join("\n");
|
|
508
|
+
}
|
|
509
|
+
if (result.secretExposures.length > 0) {
|
|
510
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.red(`\u2716 Possible Public Secret Exposure (${result.secretExposures.length})`)));
|
|
511
|
+
for (const item of result.secretExposures) {
|
|
512
|
+
lines.push(
|
|
513
|
+
` ${import_picocolors.default.red("\u2022")} ${import_picocolors.default.bold(item.name)} ${import_picocolors.default.dim(
|
|
514
|
+
`(public prefix "${item.prefix}" + sensitive "${item.matchedKeyword}")`
|
|
515
|
+
)}${formatRefs(item.references)}`
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
lines.push("");
|
|
519
|
+
}
|
|
520
|
+
if (!skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
521
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
|
|
522
|
+
for (const key of result.missingInEnv) {
|
|
523
|
+
lines.push(` ${import_picocolors.default.red("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
|
|
524
|
+
}
|
|
525
|
+
lines.push("");
|
|
526
|
+
} else if (skipMissingInEnv && result.missingInEnv.length > 0) {
|
|
527
|
+
lines.push(
|
|
528
|
+
import_picocolors.default.dim(`\u2139 No ${envFile} file found \u2014 skipped local ${envFile} check in CI mode`)
|
|
529
|
+
);
|
|
530
|
+
lines.push("");
|
|
531
|
+
}
|
|
532
|
+
if (result.missingInExample.length > 0) {
|
|
533
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.yellow(`\u26A0 Missing in ${exampleFile} (${result.missingInExample.length})`)));
|
|
534
|
+
for (const key of result.missingInExample) {
|
|
535
|
+
lines.push(` ${import_picocolors.default.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
|
|
536
|
+
}
|
|
537
|
+
lines.push("");
|
|
538
|
+
}
|
|
539
|
+
if (result.unusedInEnv.length > 0) {
|
|
540
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
|
|
541
|
+
for (const key of result.unusedInEnv) {
|
|
542
|
+
lines.push(` ${import_picocolors.default.dim("\u2022")} ${key}`);
|
|
543
|
+
}
|
|
544
|
+
lines.push("");
|
|
545
|
+
}
|
|
546
|
+
if (result.unusedInExample.length > 0) {
|
|
547
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.cyan(`\u25CB Unused in ${exampleFile} (${result.unusedInExample.length})`)));
|
|
548
|
+
for (const key of result.unusedInExample) {
|
|
549
|
+
lines.push(` ${import_picocolors.default.dim("\u2022")} ${key}`);
|
|
550
|
+
}
|
|
551
|
+
lines.push("");
|
|
552
|
+
}
|
|
553
|
+
if (result.duplicateKeys.env.length > 0 || result.duplicateKeys.example.length > 0) {
|
|
554
|
+
lines.push(import_picocolors.default.bold(import_picocolors.default.yellow("\u26A0 Duplicate Keys")));
|
|
555
|
+
for (const key of result.duplicateKeys.env) {
|
|
556
|
+
lines.push(` ${import_picocolors.default.yellow("\u2022")} ${key} ${import_picocolors.default.dim(`in ${envFile}`)}`);
|
|
557
|
+
}
|
|
558
|
+
for (const key of result.duplicateKeys.example) {
|
|
559
|
+
lines.push(` ${import_picocolors.default.yellow("\u2022")} ${key} ${import_picocolors.default.dim(`in ${exampleFile}`)}`);
|
|
560
|
+
}
|
|
561
|
+
lines.push("");
|
|
562
|
+
}
|
|
563
|
+
if (result.missingInExample.length > 0) {
|
|
564
|
+
lines.push(
|
|
565
|
+
import_picocolors.default.dim(`Tip: Run with ${import_picocolors.default.white("--sync")} to safely append missing keys to ${exampleFile}.`)
|
|
566
|
+
);
|
|
567
|
+
lines.push("");
|
|
568
|
+
}
|
|
569
|
+
return lines.join("\n");
|
|
570
|
+
}
|
|
571
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
572
|
+
0 && (module.exports = {
|
|
573
|
+
BUILTIN_ENV_VARS,
|
|
574
|
+
DEFAULT_EXTENSIONS,
|
|
575
|
+
DEFAULT_IGNORE_DIRS,
|
|
576
|
+
PUBLIC_ENV_PREFIXES,
|
|
577
|
+
SENSITIVE_KEYWORDS,
|
|
578
|
+
auditEnv,
|
|
579
|
+
detectSecretExposure,
|
|
580
|
+
extractEnvReferences,
|
|
581
|
+
formatAuditReport,
|
|
582
|
+
generateEnvTypes,
|
|
583
|
+
hasBlockingIssues,
|
|
584
|
+
parseEnvContent,
|
|
585
|
+
parseEnvFile,
|
|
586
|
+
scanFiles,
|
|
587
|
+
syncEnvExample,
|
|
588
|
+
writeEnvTypes
|
|
589
|
+
});
|