@pavol-baker/envaudit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +245 -3
- package/bin/envaudit.js +4 -0
- package/package.json +46 -4
- package/src/analyze.js +215 -0
- package/src/cli.js +187 -0
- package/src/config.js +110 -0
- package/src/dotenv.js +80 -0
- package/src/extractors.js +295 -0
- package/src/glob.js +59 -0
- package/src/index.js +6 -0
- package/src/report.js +168 -0
- package/src/scan.js +102 -0
- package/src/secrets.js +27 -0
- package/src/sync.js +62 -0
package/src/glob.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Tiny glob -> RegExp converter. Supports `**`, `*`, `?` and `{a,b}`.
|
|
2
|
+
// Patterns without a slash match against any path segment suffix
|
|
3
|
+
// (like .gitignore): `dist` matches `dist`, `a/dist` and `a/dist/x.js`.
|
|
4
|
+
|
|
5
|
+
export function globToRegExp(pattern) {
|
|
6
|
+
let p = pattern.replace(/\\/g, '/').trim();
|
|
7
|
+
const anchored = p.startsWith('/');
|
|
8
|
+
if (anchored) p = p.slice(1);
|
|
9
|
+
if (p.endsWith('/')) p = p.slice(0, -1);
|
|
10
|
+
const hasSlash = p.includes('/');
|
|
11
|
+
|
|
12
|
+
let re = '';
|
|
13
|
+
for (let i = 0; i < p.length; i++) {
|
|
14
|
+
const c = p[i];
|
|
15
|
+
if (c === '*') {
|
|
16
|
+
if (p[i + 1] === '*') {
|
|
17
|
+
// `**/` matches zero or more directories, trailing `**` matches anything
|
|
18
|
+
if (p[i + 2] === '/') {
|
|
19
|
+
re += '(?:.*/)?';
|
|
20
|
+
i += 2;
|
|
21
|
+
} else {
|
|
22
|
+
re += '.*';
|
|
23
|
+
i += 1;
|
|
24
|
+
}
|
|
25
|
+
} else {
|
|
26
|
+
re += '[^/]*';
|
|
27
|
+
}
|
|
28
|
+
} else if (c === '?') {
|
|
29
|
+
re += '[^/]';
|
|
30
|
+
} else if (c === '{') {
|
|
31
|
+
const end = p.indexOf('}', i);
|
|
32
|
+
if (end === -1) {
|
|
33
|
+
re += '\\{';
|
|
34
|
+
} else {
|
|
35
|
+
const alts = p.slice(i + 1, end).split(',').map(escapeRe);
|
|
36
|
+
re += `(?:${alts.join('|')})`;
|
|
37
|
+
i = end;
|
|
38
|
+
}
|
|
39
|
+
} else {
|
|
40
|
+
re += escapeRe(c);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const prefix = anchored || hasSlash ? '^' : '(?:^|/)';
|
|
45
|
+
// match the path itself or anything inside it
|
|
46
|
+
return new RegExp(`${prefix}${re}(?:/.*)?$`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function escapeRe(s) {
|
|
50
|
+
return s.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function makeMatcher(patterns) {
|
|
54
|
+
const res = patterns.filter(Boolean).map(globToRegExp);
|
|
55
|
+
return (relPath) => {
|
|
56
|
+
const p = relPath.replace(/\\/g, '/');
|
|
57
|
+
return res.some((r) => r.test(p));
|
|
58
|
+
};
|
|
59
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Public programmatic API.
|
|
2
|
+
export { audit } from './analyze.js';
|
|
3
|
+
export { planSync, applySync } from './sync.js';
|
|
4
|
+
export { extract, languageFor, LANGUAGES } from './extractors.js';
|
|
5
|
+
export { parseDotenv } from './dotenv.js';
|
|
6
|
+
export { formatPretty, formatJson, formatGithub } from './report.js';
|
package/src/report.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Output formatters: human-friendly terminal output, JSON, and GitHub annotations.
|
|
2
|
+
|
|
3
|
+
export function makeColors(enabled) {
|
|
4
|
+
const wrap = (open, close) => (s) => (enabled ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
|
|
5
|
+
return {
|
|
6
|
+
bold: wrap(1, 22), dim: wrap(2, 22), red: wrap(31, 39), green: wrap(32, 39),
|
|
7
|
+
yellow: wrap(33, 39), blue: wrap(34, 39), cyan: wrap(36, 39), gray: wrap(90, 39),
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function shouldUseColor(stream, flag) {
|
|
12
|
+
if (flag === false) return false;
|
|
13
|
+
if (flag === true) return true;
|
|
14
|
+
if (process.env.NO_COLOR) return false;
|
|
15
|
+
if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0') return true;
|
|
16
|
+
return Boolean(stream.isTTY);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const loc = (l) => `${l.file}:${l.line}:${l.column}`;
|
|
20
|
+
|
|
21
|
+
/** Pretty, human-readable report. */
|
|
22
|
+
export function formatPretty(result, { color = false, verbose = false } = {}) {
|
|
23
|
+
const c = makeColors(color);
|
|
24
|
+
const out = [];
|
|
25
|
+
const multi = result.scopes.length > 1;
|
|
26
|
+
const pad = (names) => Math.min(Math.max(0, ...names.map((n) => n.length)) + 2, 40);
|
|
27
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
28
|
+
|
|
29
|
+
out.push(
|
|
30
|
+
`${c.bold('envaudit')} ${c.gray('·')} ${plural(result.filesScanned, 'source file')} scanned` +
|
|
31
|
+
(result.configSource ? c.gray(` · config: ${result.configSource}`) : ''),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
for (const s of result.scopes) {
|
|
35
|
+
const exampleLabel = s.exampleFiles.length ? s.exampleFiles.join(', ') : c.yellow('no .env.example yet');
|
|
36
|
+
const header = multi ? `${c.bold(s.dir || '(root)')} ${c.gray('—')} ` : '';
|
|
37
|
+
const docCount = [...s.documented.values()].length;
|
|
38
|
+
out.push('');
|
|
39
|
+
out.push(`${header}${exampleLabel}${s.exampleFiles.length ? c.gray(` · ${plural(docCount, 'variable')} documented`) : ''}`);
|
|
40
|
+
|
|
41
|
+
const clean =
|
|
42
|
+
!s.undocumented.length && !s.unused.length && !s.missingLocal.length && !s.duplicates.length &&
|
|
43
|
+
!s.secrets.length && s.envGitStatus !== 'tracked' && s.envGitStatus !== 'untracked';
|
|
44
|
+
if (clean) {
|
|
45
|
+
out.push(` ${c.green('✔')} ${c.gray(`in sync (${plural(s.refs.size, 'variable')} referenced in code)`)}`);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (s.secrets.length) {
|
|
50
|
+
out.push(` ${c.red('✖')} ${c.bold('Looks like a real secret in an example file')} ${c.gray('(rotate it!)')}`);
|
|
51
|
+
for (const x of s.secrets) out.push(` ${c.red(x.name)} ${c.gray(`${x.file}:${x.line}`)} ${x.kind}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (s.envGitStatus === 'tracked') {
|
|
55
|
+
out.push(` ${c.red('✖')} ${c.bold(`${s.envFile} is committed to git`)} ${c.gray(`→ git rm --cached ${s.envFile} && echo ${baseName(s.envFile)} >> .gitignore`)}`);
|
|
56
|
+
} else if (s.envGitStatus === 'untracked') {
|
|
57
|
+
out.push(` ${c.yellow('⚠')} ${c.bold(`${s.envFile} is not in .gitignore`)} ${c.gray('— one `git add .` away from leaking secrets')}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (s.undocumented.length) {
|
|
61
|
+
const target = s.exampleFiles[0] ?? '.env.example';
|
|
62
|
+
out.push(` ${c.red('✖')} ${c.bold(`Undocumented (${s.undocumented.length})`)} ${c.gray(`— used in code, missing from ${target}`)}`);
|
|
63
|
+
const w = pad(s.undocumented.map((u) => u.name));
|
|
64
|
+
for (const u of s.undocumented) {
|
|
65
|
+
const shown = verbose ? u.refs : u.refs.slice(0, 2);
|
|
66
|
+
const more = u.refs.length - shown.length;
|
|
67
|
+
out.push(` ${c.red(u.name.padEnd(w))}${c.cyan(shown.map(loc).join(', '))}${more ? c.gray(` +${more} more`) : ''}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (s.unused.length) {
|
|
72
|
+
out.push(` ${c.yellow('⚠')} ${c.bold(`Unused (${s.unused.length})`)} ${c.gray('— documented but never referenced')}`);
|
|
73
|
+
const w = pad(s.unused.map((u) => u.name));
|
|
74
|
+
for (const u of s.unused) out.push(` ${c.yellow(u.name.padEnd(w))}${c.gray(`${u.file}:${u.line}`)}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (s.duplicates.length) {
|
|
78
|
+
out.push(` ${c.yellow('⚠')} ${c.bold(`Duplicate keys (${s.duplicates.length})`)} ${c.gray('— the last one silently wins')}`);
|
|
79
|
+
for (const d of s.duplicates) out.push(` ${c.yellow(d.name)} ${c.gray(`${d.file}:${d.line} (first at line ${d.firstLine})`)}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (s.missingLocal.length) {
|
|
83
|
+
out.push(` ${c.blue('ℹ')} ${c.bold(`Missing from your ${s.envFile} (${s.missingLocal.length})`)} ${c.gray('— your app may crash locally')}`);
|
|
84
|
+
out.push(` ${c.blue(s.missingLocal.join(', '))}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (result.uncovered.length) {
|
|
89
|
+
out.push('');
|
|
90
|
+
out.push(`${c.blue('ℹ')} ${c.bold(`Not covered by any example file (${result.uncovered.length})`)}`);
|
|
91
|
+
const w = pad(result.uncovered.map((u) => u.name));
|
|
92
|
+
for (const u of result.uncovered) out.push(` ${u.name.padEnd(w)}${c.gray(loc(u.refs[0]))}${u.refs.length > 1 ? c.gray(` +${u.refs.length - 1} more`) : ''}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// summary line
|
|
96
|
+
const k = result.counts;
|
|
97
|
+
const errors = k.undocumented + k.secrets + k.committedEnv;
|
|
98
|
+
const warnings = k.unused + k.duplicates + k.exposedEnv;
|
|
99
|
+
out.push('');
|
|
100
|
+
if (errors === 0 && warnings === 0) {
|
|
101
|
+
out.push(c.green(c.bold('✔ All environment variables are documented.')));
|
|
102
|
+
} else {
|
|
103
|
+
const parts = [];
|
|
104
|
+
if (errors) parts.push(c.red(plural(errors, 'error')));
|
|
105
|
+
if (warnings) parts.push(c.yellow(plural(warnings, 'warning')));
|
|
106
|
+
out.push(`${result.ok ? c.yellow('!') : c.red('✖')} ${parts.join(', ')}`);
|
|
107
|
+
const hints = [];
|
|
108
|
+
if (k.undocumented) hints.push(`run ${c.cyan('npx @pavol-baker/envaudit sync')} to add the missing keys to your example file`);
|
|
109
|
+
if (k.unused) hints.push(`remove stale keys with ${c.cyan('npx @pavol-baker/envaudit sync --prune')}, or list library-only vars under "ignoreUnused" in envaudit.config.json`);
|
|
110
|
+
for (const h of hints) out.push(c.gray(` → ${h}`));
|
|
111
|
+
}
|
|
112
|
+
return out.join('\n') + '\n';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Machine-readable JSON. */
|
|
116
|
+
export function formatJson(result) {
|
|
117
|
+
const scopes = result.scopes.map((s) => ({
|
|
118
|
+
dir: s.dir,
|
|
119
|
+
exampleFiles: s.exampleFiles,
|
|
120
|
+
envFile: s.envFile,
|
|
121
|
+
envGitStatus: s.envGitStatus,
|
|
122
|
+
documented: Object.fromEntries([...s.documented].map(([k, v]) => [k, { file: v.file, line: v.line, optional: v.optional }])),
|
|
123
|
+
referenced: Object.fromEntries(s.refs),
|
|
124
|
+
undocumented: s.undocumented,
|
|
125
|
+
unused: s.unused,
|
|
126
|
+
missingLocal: s.missingLocal,
|
|
127
|
+
duplicates: s.duplicates,
|
|
128
|
+
secrets: s.secrets,
|
|
129
|
+
}));
|
|
130
|
+
return JSON.stringify(
|
|
131
|
+
{ ok: result.ok, filesScanned: result.filesScanned, counts: result.counts, scopes, uncovered: result.uncovered },
|
|
132
|
+
null,
|
|
133
|
+
2,
|
|
134
|
+
) + '\n';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** GitHub Actions workflow commands: inline annotations on the PR diff. */
|
|
138
|
+
export function formatGithub(result) {
|
|
139
|
+
const out = [];
|
|
140
|
+
const esc = (s) => String(s).replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
|
141
|
+
const prop = (s) => esc(s).replace(/:/g, '%3A').replace(/,/g, '%2C');
|
|
142
|
+
const ann = (level, { file, line, column }, title, msg) =>
|
|
143
|
+
out.push(`::${level} file=${prop(file)},line=${line}${column ? `,col=${column}` : ''},title=${prop(title)}::${esc(msg)}`);
|
|
144
|
+
|
|
145
|
+
for (const s of result.scopes) {
|
|
146
|
+
const target = s.exampleFiles[0] ?? posixJoin(s.dir, '.env.example');
|
|
147
|
+
for (const u of s.undocumented) {
|
|
148
|
+
for (const r of u.refs.slice(0, 10)) {
|
|
149
|
+
ann('error', r, 'Undocumented env var', `${u.name} is used here but missing from ${target}. Run \`npx @pavol-baker/envaudit sync\` to add it.`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (const u of s.unused) {
|
|
153
|
+
ann('warning', u, 'Unused env var', `${u.name} is documented in ${u.file} but never referenced in code.`);
|
|
154
|
+
}
|
|
155
|
+
for (const d of s.duplicates) ann('warning', d, 'Duplicate env key', `${d.name} is defined twice (first at line ${d.firstLine}).`);
|
|
156
|
+
for (const x of s.secrets) ann('error', x, 'Secret in example file', `${x.name} looks like a real ${x.kind}. Remove it and rotate the credential.`);
|
|
157
|
+
if (s.envGitStatus === 'tracked') ann('error', { file: s.envFile, line: 1 }, 'Committed .env file', `${s.envFile} is committed to git.`);
|
|
158
|
+
}
|
|
159
|
+
return out.length ? out.join('\n') + '\n' : '';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function baseName(p) {
|
|
163
|
+
return p.split('/').pop();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function posixJoin(dir, f) {
|
|
167
|
+
return dir ? `${dir}/${f}` : f;
|
|
168
|
+
}
|
package/src/scan.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { readdirSync, statSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join, relative, sep } from 'node:path';
|
|
4
|
+
import { makeMatcher } from './glob.js';
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_IGNORE_DIRS = [
|
|
7
|
+
'node_modules', '.git', '.hg', '.svn', 'dist', 'build', 'out', 'target', 'vendor',
|
|
8
|
+
'.next', '.nuxt', '.svelte-kit', '.output', '.turbo', '.cache', '.parcel-cache',
|
|
9
|
+
'coverage', '.venv', 'venv', '__pycache__', '.tox', '.mypy_cache', '.pytest_cache',
|
|
10
|
+
'.gradle', '.idea', '.vscode', 'bin/Debug', 'bin/Release', 'obj', '_build',
|
|
11
|
+
'Pods', '.dart_tool', '.terraform',
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
const MAX_FILE_BYTES = 1024 * 1024; // skip minified bundles and other huge files
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* List files under `root`. Uses `git ls-files` when available so .gitignore
|
|
18
|
+
* is respected exactly; falls back to a directory walk with sane defaults.
|
|
19
|
+
* @returns {string[]} paths relative to root, with forward slashes
|
|
20
|
+
*/
|
|
21
|
+
export function listFiles(root, { ignore = [] } = {}) {
|
|
22
|
+
const isIgnored = makeMatcher([...DEFAULT_IGNORE_DIRS, ...ignore]);
|
|
23
|
+
let files = gitFiles(root);
|
|
24
|
+
if (!files) files = walk(root, isIgnored);
|
|
25
|
+
return files.filter((f) => !isIgnored(f)).sort();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function gitFiles(root) {
|
|
29
|
+
try {
|
|
30
|
+
const out = execFileSync(
|
|
31
|
+
'git',
|
|
32
|
+
['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--deduplicate'],
|
|
33
|
+
{ cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 },
|
|
34
|
+
);
|
|
35
|
+
return out.split('\0').filter(Boolean);
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function walk(root, isIgnored) {
|
|
42
|
+
const out = [];
|
|
43
|
+
const stack = [''];
|
|
44
|
+
while (stack.length) {
|
|
45
|
+
const dir = stack.pop();
|
|
46
|
+
let entries;
|
|
47
|
+
try {
|
|
48
|
+
entries = readdirSync(join(root, dir), { withFileTypes: true });
|
|
49
|
+
} catch {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
for (const e of entries) {
|
|
53
|
+
const rel = dir ? `${dir}/${e.name}` : e.name;
|
|
54
|
+
if (isIgnored(rel)) continue;
|
|
55
|
+
if (e.isDirectory()) stack.push(rel);
|
|
56
|
+
else if (e.isFile()) out.push(rel);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Read a text file, or return null for binary / huge / unreadable files. */
|
|
63
|
+
export function readText(absPath) {
|
|
64
|
+
try {
|
|
65
|
+
const st = statSync(absPath);
|
|
66
|
+
if (!st.isFile() || st.size > MAX_FILE_BYTES) return null;
|
|
67
|
+
const buf = readFileSync(absPath);
|
|
68
|
+
if (buf.subarray(0, 8000).includes(0)) return null; // binary
|
|
69
|
+
return buf.toString('utf8');
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function toPosix(p) {
|
|
76
|
+
return p.split(sep).join('/');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function rel(from, to) {
|
|
80
|
+
return toPosix(relative(from, to));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function git(root, args) {
|
|
84
|
+
try {
|
|
85
|
+
return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Git status of a file: 'tracked' (committed - bad for .env!), 'ignored',
|
|
93
|
+
* 'untracked' (not ignored, one `git add .` away from a leak) or null if
|
|
94
|
+
* root is not inside a git repository.
|
|
95
|
+
*/
|
|
96
|
+
export function gitStatusOf(root, relPath) {
|
|
97
|
+
if (git(root, ['rev-parse', '--is-inside-work-tree']) === null) return null;
|
|
98
|
+
const tracked = git(root, ['ls-files', '--', relPath]);
|
|
99
|
+
if (tracked && tracked.trim()) return 'tracked';
|
|
100
|
+
const ignored = git(root, ['check-ignore', '-q', '--', relPath]);
|
|
101
|
+
return ignored !== null ? 'ignored' : 'untracked';
|
|
102
|
+
}
|
package/src/secrets.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Real credentials that sometimes end up in .env.example by accident.
|
|
2
|
+
// Deliberately high-precision: we only flag well-known key formats.
|
|
3
|
+
|
|
4
|
+
const PATTERNS = [
|
|
5
|
+
['AWS access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],
|
|
6
|
+
['Stripe live key', /\b(?:sk|rk)_live_[0-9a-zA-Z]{20,}\b/],
|
|
7
|
+
['GitHub token', /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{50,}\b/],
|
|
8
|
+
['GitLab token', /\bglpat-[A-Za-z0-9_-]{20,}\b/],
|
|
9
|
+
['Slack token', /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/],
|
|
10
|
+
['Slack webhook', /hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{20,}/],
|
|
11
|
+
['Google API key', /\bAIza[0-9A-Za-z_-]{35}\b/],
|
|
12
|
+
['Anthropic API key', /\bsk-ant-[A-Za-z0-9_-]{20,}\b/],
|
|
13
|
+
['OpenAI API key', /\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}\b/],
|
|
14
|
+
['SendGrid key', /\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b/],
|
|
15
|
+
['Twilio key', /\bSK[0-9a-f]{32}\b/],
|
|
16
|
+
['npm token', /\bnpm_[A-Za-z0-9]{36}\b/],
|
|
17
|
+
['Private key', /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY/],
|
|
18
|
+
['Connection string with password', /\b[a-z][a-z0-9+]*:\/\/[^:\s/@]+:(?!password\b|pass\b|secret\b|changeme\b|postgres\b|root\b|example\b|\$\{|<|\*)[^@\s]{6,}@(?!localhost\b|127\.0\.0\.1\b|db\b|postgres\b|mysql\b|redis\b|mongo\b|host\b|example\.)/i],
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
/** @returns {string|null} a description of the secret found, or null */
|
|
22
|
+
export function detectSecret(value) {
|
|
23
|
+
if (!value || value.length < 16) return null;
|
|
24
|
+
if (/example|placeholder|xxxx|your[_-]/i.test(value)) return null; // documented dummy values
|
|
25
|
+
for (const [label, re] of PATTERNS) if (re.test(value)) return label;
|
|
26
|
+
return null;
|
|
27
|
+
}
|
package/src/sync.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { parseDotenv } from './dotenv.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Plan the edits needed to bring example files in sync with the code.
|
|
7
|
+
* Pure: returns a list of file changes, writes nothing.
|
|
8
|
+
* @param {ReturnType<import('./analyze.js').audit>} result
|
|
9
|
+
* @param {{ prune?: boolean }} opts
|
|
10
|
+
* @returns {{ file: string, created: boolean, added: string[], removed: string[], content: string }[]}
|
|
11
|
+
*/
|
|
12
|
+
export function planSync(result, { prune = false } = {}) {
|
|
13
|
+
const changes = [];
|
|
14
|
+
for (const s of result.scopes) {
|
|
15
|
+
const target = s.exampleFiles[0] ?? (s.dir ? `${s.dir}/.env.example` : '.env.example');
|
|
16
|
+
const abs = join(result.root, target);
|
|
17
|
+
const exists = existsSync(abs);
|
|
18
|
+
let text = exists ? readFileSync(abs, 'utf8') : '';
|
|
19
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
20
|
+
const removed = [];
|
|
21
|
+
|
|
22
|
+
if (prune && s.unused.length) {
|
|
23
|
+
// only prune from the target file; unused keys in other example files are reported, not touched
|
|
24
|
+
const unused = new Set(s.unused.filter((u) => u.file === target).map((u) => u.name));
|
|
25
|
+
const { entries } = parseDotenv(text);
|
|
26
|
+
const drop = new Set();
|
|
27
|
+
for (const e of entries) {
|
|
28
|
+
if (e.optional || !unused.has(e.name)) continue;
|
|
29
|
+
for (let l = e.line; l <= e.endLine; l++) drop.add(l);
|
|
30
|
+
removed.push(e.name);
|
|
31
|
+
}
|
|
32
|
+
text = text
|
|
33
|
+
.split(/\r?\n/)
|
|
34
|
+
.filter((_, i) => !drop.has(i + 1))
|
|
35
|
+
.join(eol);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const added = s.undocumented.map((u) => u.name);
|
|
39
|
+
if (added.length) {
|
|
40
|
+
const block = [];
|
|
41
|
+
if (!exists) block.push('# Environment variables used by this project.', '# Copy this file to .env and fill in the values.', '');
|
|
42
|
+
for (const u of s.undocumented) {
|
|
43
|
+
const first = u.refs[0];
|
|
44
|
+
const where = `${first.file}:${first.line}`;
|
|
45
|
+
block.push(`# used in ${where}${u.refs.length > 1 ? ` (+${u.refs.length - 1} more)` : ''}`);
|
|
46
|
+
block.push(`${u.name}=`);
|
|
47
|
+
}
|
|
48
|
+
if (text && !/\r?\n$/.test(text)) text += eol;
|
|
49
|
+
if (text && !/(\r?\n){2}$/.test(text)) text += eol;
|
|
50
|
+
text += block.join(eol) + eol;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (added.length || removed.length) {
|
|
54
|
+
changes.push({ file: target, created: !exists, added, removed: [...new Set(removed)], content: text });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return changes;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function applySync(root, changes) {
|
|
61
|
+
for (const ch of changes) writeFileSync(join(root, ch.file), ch.content, 'utf8');
|
|
62
|
+
}
|