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