@jutaru-dev/envsonar 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 +176 -3
- package/bin/envsonar.js +11 -0
- package/package.json +46 -6
- package/src/check.js +146 -0
- package/src/cli.js +298 -0
- package/src/index.js +5 -0
- package/src/parse.js +98 -0
- package/src/profiles.js +80 -0
- package/src/scan.js +557 -0
package/src/scan.js
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, extname, join, relative, sep } from "node:path";
|
|
4
|
+
import { PROFILES } from "./profiles.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {{ optional?: boolean, ci?: boolean }} Flags
|
|
8
|
+
* optional — the code has a fallback value; ci — the name is matched case-insensitively (.NET config, pydantic)
|
|
9
|
+
* @typedef {{ file: string, line: number } & Flags} Usage
|
|
10
|
+
* @typedef {{ key: string, line: number } & Flags} Found
|
|
11
|
+
* @typedef {{ file: string, line: number, expr: string }} DynamicRead
|
|
12
|
+
* @typedef {{ source: string, keys: string[] }} Implicit
|
|
13
|
+
* @typedef {{
|
|
14
|
+
* files: number,
|
|
15
|
+
* usages: Map<string, Usage[]>,
|
|
16
|
+
* sections: Map<string, Usage[]>,
|
|
17
|
+
* dynamic: DynamicRead[],
|
|
18
|
+
* provided: Map<string, { key: string, source: string }>,
|
|
19
|
+
* implicit: Implicit[],
|
|
20
|
+
* }} ScanResult
|
|
21
|
+
* @typedef {{
|
|
22
|
+
* add: (key: string, line: number, flags?: Flags) => void,
|
|
23
|
+
* section: (prefix: string, line: number) => void,
|
|
24
|
+
* dynamic: (expr: string, line: number) => void,
|
|
25
|
+
* provide: (key: string, source: string) => void,
|
|
26
|
+
* mark: (marker: string) => void,
|
|
27
|
+
* lineAt: (offset: number) => number,
|
|
28
|
+
* }} Sink
|
|
29
|
+
* @typedef {{ re: RegExp, call?: boolean, member?: boolean, optional?: boolean }} Pattern
|
|
30
|
+
* @typedef {{ name: string, test: (file: string) => boolean, patterns: Pattern[], extra?: (text: string, sink: Sink, file: string) => void }} Language
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const K = String.raw`(?<key>[A-Za-z_][A-Za-z0-9_]*)`;
|
|
34
|
+
const Q = String.raw`(?<q>['"\x60])`;
|
|
35
|
+
const QS = String.raw`\k<q>`;
|
|
36
|
+
const JS_ENV = String.raw`(?:process\.env|import\.meta\.env|Bun\.env)`;
|
|
37
|
+
const NET_PATH = String.raw`(?<path>[A-Za-z_][\w.-]*(?::[\w.-]+)*)`;
|
|
38
|
+
|
|
39
|
+
/** @param {string} source */
|
|
40
|
+
const re = (source) => new RegExp(source, "g");
|
|
41
|
+
/** @param {...string} exts */
|
|
42
|
+
const byExt = (...exts) => (/** @type {string} */ file) => exts.includes(extname(file).toLowerCase());
|
|
43
|
+
/** @param {RegExp} pattern */
|
|
44
|
+
const byName = (pattern) => (/** @type {string} */ file) => pattern.test(basename(file));
|
|
45
|
+
|
|
46
|
+
/** a fallback right after a call: `getenv("X", 1)`, `GetEnvironmentVariable("X") ?? "a"`, `env::var("X").unwrap_or(..)`, `ENV.fetch("X") { }` */
|
|
47
|
+
const CALL_DEFAULT = /^\s*(?:,\s*[^\s)]|\)\s*(?:\?\?|\|\||or\b|\.unwrap_or|\.or\b|\{))/;
|
|
48
|
+
/** a fallback after a property read: `process.env.X ?? "a"`, `ENV["X"] || "a"` */
|
|
49
|
+
const MEMBER_DEFAULT = /^\s*(?:\?\?|\|\|)/;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Reads through a local alias of the environment: `const env = process.env; env.KEY`, `env = dict(os.environ); env.get("KEY")`.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} text
|
|
55
|
+
* @param {string} alias
|
|
56
|
+
* @param {Sink} sink
|
|
57
|
+
* @param {"js" | "py"} lang
|
|
58
|
+
*/
|
|
59
|
+
function readsVia(text, alias, sink, lang) {
|
|
60
|
+
const n = alias.replace(/\$/g, "\\$");
|
|
61
|
+
/** @type {Pattern[]} */
|
|
62
|
+
const patterns = [
|
|
63
|
+
{ re: re(String.raw`(?<![\w$.])${n}\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
64
|
+
{ re: re(String.raw`(?<![\w$.])${n}\.(?:get|setdefault|pop)\(\s*${Q}${K}${QS}`), call: true },
|
|
65
|
+
];
|
|
66
|
+
if (lang === "js") patterns.push({ re: re(String.raw`(?<![\w$.])${n}\.${K}\b(?!\s*\()`), member: true });
|
|
67
|
+
applyPatterns(text, patterns, sink);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @param {string} text @param {Sink} sink */
|
|
71
|
+
function jsExtra(text, sink) {
|
|
72
|
+
// const { A, B: alias, C = "x" } = process.env
|
|
73
|
+
for (const m of text.matchAll(re(String.raw`\{([^{}]*)\}\s*=\s*${JS_ENV}\b`))) {
|
|
74
|
+
const line = sink.lineAt(m.index ?? 0);
|
|
75
|
+
for (const part of m[1].split(",")) {
|
|
76
|
+
const name = part.trim().split(/[:=\s]/)[0];
|
|
77
|
+
if (/^[A-Za-z_]\w*$/.test(name)) sink.add(name, line, { optional: part.includes("=") });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const aliases = [...text.matchAll(re(String.raw`\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*${JS_ENV}\s*(?=[;\n]|$)`))].map((m) => m[1]);
|
|
82
|
+
|
|
83
|
+
// SvelteKit: import { PUBLIC_API } from "$env/static/public"; import { env } from "$env/dynamic/private"
|
|
84
|
+
for (const m of text.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\$env\/(static|dynamic)\/(?:public|private)['"]/g)) {
|
|
85
|
+
const line = sink.lineAt(m.index ?? 0);
|
|
86
|
+
for (const part of m[1].split(",")) {
|
|
87
|
+
const [name, , local] = part.trim().split(/\s+/);
|
|
88
|
+
if (m[2] === "dynamic" && name === "env") aliases.push(local ?? "env");
|
|
89
|
+
else if (name && /^[A-Za-z_]\w*$/.test(name)) sink.add(name, line);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const alias of aliases) readsVia(text, alias, sink, "js");
|
|
93
|
+
|
|
94
|
+
for (const m of text.matchAll(re(String.raw`\b${JS_ENV}\[([^\]\n]{1,80})\]`))) {
|
|
95
|
+
if (!/^\s*(['"`])[A-Za-z_]\w*\1\s*$/.test(m[1])) sink.dynamic(m[0], sink.lineAt(m.index ?? 0));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// envalid: cleanEnv(process.env, { PORT: port({ default: 3000 }) })
|
|
99
|
+
if (/\bcleanEnv\s*\(/.test(text)) {
|
|
100
|
+
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*(?:str|num|bool|port|url|email|host|json)\s*\(([^()\n]*)/g)) {
|
|
101
|
+
sink.add(m[1], sink.lineAt(m.index ?? 0), { optional: /\bdefault\s*:/.test(m[2]) });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// zod schemas parsed from the environment, and @t3-oss/env: createEnv({ server: { DATABASE_URL: z.string() } })
|
|
105
|
+
if (/\bcreateEnv\s*\(|\b(?:safeParse|parse)\(\s*(?:process\.env|import\.meta\.env)\b/.test(text)) {
|
|
106
|
+
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*z\s*\.([^\n]*)/g)) {
|
|
107
|
+
sink.add(m[1], sink.lineAt(m.index ?? 0), { optional: /\.(?:default|optional)\(/.test(m[2]) });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** @param {string} text @param {Sink} sink */
|
|
113
|
+
function pyExtra(text, sink) {
|
|
114
|
+
for (const m of text.matchAll(/^[ \t]*([A-Za-z_]\w*)\s*=\s*(?:dict\(\s*)?(?:os\.)?environ\b(?:\.copy\(\))?\s*\)?[ \t]*(?:#.*)?$/gm)) {
|
|
115
|
+
readsVia(text, m[1], sink, "py");
|
|
116
|
+
}
|
|
117
|
+
for (const m of text.matchAll(/\b(?:getenv|environ\.get)\(\s*[A-Za-z_][\w.]*\s*[,)]|\benviron\[\s*[A-Za-z_][\w.]*\s*\]/g)) {
|
|
118
|
+
sink.dynamic(m[0].replace(/\s*,$/, ")"), sink.lineAt(m.index ?? 0));
|
|
119
|
+
}
|
|
120
|
+
pydanticSettings(text, sink);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* pydantic-settings: every field of a `BaseSettings` class is an environment variable,
|
|
125
|
+
* named after the field (case-insensitive) with the class's `env_prefix`, unless it has an alias.
|
|
126
|
+
*
|
|
127
|
+
* @param {string} text
|
|
128
|
+
* @param {Sink} sink
|
|
129
|
+
*/
|
|
130
|
+
function pydanticSettings(text, sink) {
|
|
131
|
+
if (!text.includes("BaseSettings")) return;
|
|
132
|
+
const lines = text.split(/\r?\n/);
|
|
133
|
+
const indentOf = (/** @type {string} */ l) => l.length - l.trimStart().length;
|
|
134
|
+
for (let i = 0; i < lines.length; i++) {
|
|
135
|
+
const head = /^([ \t]*)class\s+\w+\s*\(([^)]*)\)\s*:/.exec(lines[i]);
|
|
136
|
+
if (!head || !/\bBaseSettings\b/.test(head[2])) continue;
|
|
137
|
+
/** @type {[number, string][]} */
|
|
138
|
+
const body = [];
|
|
139
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
140
|
+
const l = lines[j];
|
|
141
|
+
if (!l.trim() || l.trim().startsWith("#")) continue;
|
|
142
|
+
if (indentOf(l) <= head[1].length) break;
|
|
143
|
+
body.push([j, l]);
|
|
144
|
+
}
|
|
145
|
+
if (!body.length) continue;
|
|
146
|
+
const fieldIndent = indentOf(body[0][1]);
|
|
147
|
+
const prefix = /env_prefix\s*[=:]\s*['"]([^'"]*)['"]/.exec(body.map(([, l]) => l).join("\n"))?.[1] ?? "";
|
|
148
|
+
for (const [j, l] of body) {
|
|
149
|
+
if (indentOf(l) !== fieldIndent) continue;
|
|
150
|
+
const f = /^\s*([A-Za-z_]\w*)\s*:\s*([^=]*?)\s*(?:=\s*(.*))?$/.exec(l);
|
|
151
|
+
if (!f || f[1] === "model_config" || f[1].startsWith("_") || /\bClassVar\b/.test(f[2])) continue;
|
|
152
|
+
const value = f[3]?.trim();
|
|
153
|
+
const alias = /\b(?:validation_)?alias\s*=\s*['"]([^'"]+)['"]/.exec(value ?? "")?.[1];
|
|
154
|
+
const optional =
|
|
155
|
+
value !== undefined &&
|
|
156
|
+
(!value.startsWith("Field(") || /\bdefault(?:_factory)?\s*=/.test(value) || /^Field\(\s*(?![.)]|\w+\s*=)/.test(value));
|
|
157
|
+
sink.add(alias ?? (prefix + f[1]).toUpperCase(), j + 1, { ci: true, optional });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** @param {string} path */
|
|
163
|
+
const netKey = (path) => path.replace(/:/g, "__");
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* .NET configuration: `config["Jwt:Key"]`, `GetValue<T>("Jwt:Key")`, `GetConnectionString("Db")` read the
|
|
167
|
+
* environment variables `Jwt__Key` and `ConnectionStrings__Db`; `GetSection("Jwt")` binds everything under `Jwt__`.
|
|
168
|
+
*
|
|
169
|
+
* @param {string} text
|
|
170
|
+
* @param {Sink} sink
|
|
171
|
+
*/
|
|
172
|
+
function csExtra(text, sink) {
|
|
173
|
+
/** @type {[RegExp, (m: RegExpMatchArray) => string][]} */
|
|
174
|
+
const reads = [
|
|
175
|
+
[re(String.raw`\b(?:[\w.]*[Cc]onfig\w*|Configuration)\s*\[\s*"${NET_PATH}"\s*\]`), (m) => netKey(m.groups?.path ?? "")],
|
|
176
|
+
[re(String.raw`\.GetValue(?:<[^>()]+>)?\(\s*"${NET_PATH}"`), (m) => netKey(m.groups?.path ?? "")],
|
|
177
|
+
[/\.GetConnectionString\(\s*"(?<name>[\w.-]+)"/g, (m) => `ConnectionStrings__${m.groups?.name}`],
|
|
178
|
+
];
|
|
179
|
+
for (const [pattern, keyOf] of reads) {
|
|
180
|
+
for (const m of text.matchAll(pattern)) {
|
|
181
|
+
const end = (m.index ?? 0) + m[0].length;
|
|
182
|
+
const after = text.slice(end, end + 40);
|
|
183
|
+
sink.add(keyOf(m), sink.lineAt(m.index ?? 0), { ci: true, optional: CALL_DEFAULT.test(after) || MEMBER_DEFAULT.test(after) });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
for (const m of text.matchAll(re(String.raw`\.(?:GetSection|GetRequiredSection|BindConfiguration)\(\s*"${NET_PATH}"`))) {
|
|
187
|
+
sink.section(`${netKey(m.groups?.path ?? "")}__`, sink.lineAt(m.index ?? 0));
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Struct tags of caarlos0/env and kelseyhightower/envconfig: `env:"PORT" envDefault:"3000"`. @param {string} text @param {Sink} sink */
|
|
192
|
+
function goExtra(text, sink) {
|
|
193
|
+
for (const m of text.matchAll(/`([^`\n]*)`/g)) {
|
|
194
|
+
const tag = /(?:^|\s)(?:env|envconfig):"([A-Za-z_][A-Za-z0-9_]*)/.exec(m[1]);
|
|
195
|
+
if (tag) sink.add(tag[1], sink.lineAt(m.index ?? 0), { optional: /\b(?:envDefault|default):"/.test(m[1]) });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Compose files: `environment:` entries give the container a value, so the app needs no .env entry for them;
|
|
201
|
+
* the images in use tell which variables are read implicitly (postgres reads POSTGRES_PASSWORD).
|
|
202
|
+
*
|
|
203
|
+
* @param {string} text
|
|
204
|
+
* @param {Sink} sink
|
|
205
|
+
* @param {string} file
|
|
206
|
+
*/
|
|
207
|
+
function composeExtra(text, sink, file) {
|
|
208
|
+
sink.mark("compose");
|
|
209
|
+
for (const m of text.matchAll(/^\s*image:\s*["']?([^\s"'#]+)/gm)) {
|
|
210
|
+
const name = m[1].split("/").pop()?.split(/[:@]/)[0];
|
|
211
|
+
if (name) sink.mark(`image:${name.toLowerCase()}`);
|
|
212
|
+
}
|
|
213
|
+
const lines = text.split(/\r?\n/);
|
|
214
|
+
for (let i = 0; i < lines.length; i++) {
|
|
215
|
+
const head = /^(\s*)environment\s*:\s*(?:#.*)?$/.exec(lines[i]);
|
|
216
|
+
if (!head) continue;
|
|
217
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
218
|
+
const l = lines[j];
|
|
219
|
+
if (!l.trim() || l.trim().startsWith("#")) continue;
|
|
220
|
+
if (l.length - l.trimStart().length <= head[1].length) break;
|
|
221
|
+
const entry = /^\s*-?\s*["']?([A-Za-z_][\w.]*)["']?\s*[:=]\s*\S/.exec(l);
|
|
222
|
+
if (entry) sink.provide(entry[1], file);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** @type {Language[]} */
|
|
228
|
+
export const LANGUAGES = [
|
|
229
|
+
{
|
|
230
|
+
name: "JavaScript / TypeScript",
|
|
231
|
+
test: byExt(".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte", ".astro"),
|
|
232
|
+
patterns: [
|
|
233
|
+
{ re: re(String.raw`\b${JS_ENV}\.${K}\b(?!\s*\()`), member: true },
|
|
234
|
+
{ re: re(String.raw`\b${JS_ENV}\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
235
|
+
{ re: re(String.raw`\bDeno\.env\.get\(\s*${Q}${K}${QS}`), call: true },
|
|
236
|
+
],
|
|
237
|
+
extra: jsExtra,
|
|
238
|
+
},
|
|
239
|
+
{ name: "Vite index.html", test: byName(/^index\.html$/i), patterns: [{ re: /%(?<key>[A-Z][A-Z0-9_]*)%/g }] },
|
|
240
|
+
{
|
|
241
|
+
name: "Python",
|
|
242
|
+
test: byExt(".py"),
|
|
243
|
+
patterns: [
|
|
244
|
+
{ re: re(String.raw`\b(?:getenv|environ\.get|environ\.setdefault|environ\.pop)\(\s*${Q}${K}${QS}`), call: true },
|
|
245
|
+
{ re: re(String.raw`\benviron\[\s*${Q}${K}${QS}\s*\]`) },
|
|
246
|
+
],
|
|
247
|
+
extra: pyExtra,
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: "C# / .NET",
|
|
251
|
+
test: byExt(".cs"),
|
|
252
|
+
patterns: [{ re: re(String.raw`\bGetEnvironmentVariable\(\s*@?"${K}"`), call: true }],
|
|
253
|
+
extra: csExtra,
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
name: "PHP / Laravel",
|
|
257
|
+
test: byExt(".php"),
|
|
258
|
+
patterns: [
|
|
259
|
+
{ re: re(String.raw`(?<![\w$>:])(?:env|getenv)\(\s*${Q}${K}${QS}`), call: true },
|
|
260
|
+
{ re: re(String.raw`\$_ENV\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
261
|
+
],
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
name: "Go",
|
|
265
|
+
test: byExt(".go"),
|
|
266
|
+
patterns: [{ re: re(String.raw`\bos\.Getenv\(\s*"${K}"`) }, { re: re(String.raw`\bos\.LookupEnv\(\s*"${K}"`), optional: true }],
|
|
267
|
+
extra: goExtra,
|
|
268
|
+
},
|
|
269
|
+
{
|
|
270
|
+
name: "Ruby",
|
|
271
|
+
test: byExt(".rb", ".rake"),
|
|
272
|
+
patterns: [
|
|
273
|
+
{ re: re(String.raw`\bENV\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
274
|
+
{ re: re(String.raw`\bENV\.fetch\(\s*${Q}${K}${QS}`), call: true },
|
|
275
|
+
],
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
name: "Rust",
|
|
279
|
+
test: byExt(".rs"),
|
|
280
|
+
patterns: [
|
|
281
|
+
{ re: re(String.raw`\b(?:env|dotenvy?)::var(?:_os)?\(\s*"${K}"`), call: true },
|
|
282
|
+
{ re: re(String.raw`\benv!\(\s*"${K}"`) },
|
|
283
|
+
{ re: re(String.raw`\boption_env!\(\s*"${K}"`), optional: true },
|
|
284
|
+
],
|
|
285
|
+
},
|
|
286
|
+
{
|
|
287
|
+
name: "Prisma",
|
|
288
|
+
test: (file) => extname(file).toLowerCase() === ".prisma" || /^prisma\.config\.[cm]?[jt]s$/i.test(basename(file)),
|
|
289
|
+
patterns: [{ re: re(String.raw`\benv\(\s*${Q}${K}${QS}\s*\)`) }],
|
|
290
|
+
},
|
|
291
|
+
{
|
|
292
|
+
name: "Docker Compose",
|
|
293
|
+
test: byName(/^(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml$/i),
|
|
294
|
+
patterns: [{ re: /\$\{(?<key>[A-Za-z_][A-Za-z0-9_]*)(?:(?<def>:?[-?+])|(?=}))/g }, { re: /(?<![$\w])\$(?<key>[A-Za-z_][A-Za-z0-9_]*)/g }],
|
|
295
|
+
extra: composeExtra,
|
|
296
|
+
},
|
|
297
|
+
];
|
|
298
|
+
|
|
299
|
+
export const DEFAULT_IGNORE_DIRS = [
|
|
300
|
+
"node_modules", ".git", ".hg", ".svn", "dist", "build", "out", ".next", ".nuxt", ".output", ".svelte-kit",
|
|
301
|
+
".vercel", ".netlify", ".turbo", ".cache", "coverage", "vendor", "bin", "obj", "target", ".venv", "venv",
|
|
302
|
+
"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".idea", ".vscode", ".worktrees",
|
|
303
|
+
".claude", ".pnpm-store", ".yarn", ".expo", ".angular", ".gradle", "Pods", "DerivedData",
|
|
304
|
+
];
|
|
305
|
+
|
|
306
|
+
/** Keys set by the OS, runtimes and CI — nobody documents them in .env.example. */
|
|
307
|
+
export const DEFAULT_IGNORE_KEYS = [
|
|
308
|
+
"NODE_ENV", "CI", "HOME", "PATH", "PWD", "USER", "USERNAME", "SHELL", "TERM", "TZ", "LANG", "HOSTNAME",
|
|
309
|
+
"TMPDIR", "TEMP", "TMP", "APPDATA", "LOCALAPPDATA", "USERPROFILE", "MODE", "DEV", "PROD", "SSR", "BASE_URL",
|
|
310
|
+
"GITHUB_*", "RUNNER_*", "VERCEL_*", "NETLIFY_*", "npm_*", "ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT",
|
|
311
|
+
];
|
|
312
|
+
|
|
313
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* @param {string[]} patterns exact names or prefixes ending with `*`
|
|
317
|
+
* @returns {(key: string) => boolean}
|
|
318
|
+
*/
|
|
319
|
+
export function keyMatcher(patterns) {
|
|
320
|
+
const exact = new Set(patterns.filter((p) => !p.endsWith("*")));
|
|
321
|
+
const prefixes = patterns.filter((p) => p.endsWith("*")).map((p) => p.slice(0, -1));
|
|
322
|
+
return (key) => exact.has(key) || prefixes.some((p) => key.startsWith(p));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* @param {string} text
|
|
327
|
+
* @param {Pattern[]} patterns
|
|
328
|
+
* @param {Sink} sink
|
|
329
|
+
*/
|
|
330
|
+
function applyPatterns(text, patterns, sink) {
|
|
331
|
+
for (const p of patterns) {
|
|
332
|
+
for (const m of text.matchAll(p.re)) {
|
|
333
|
+
const key = m.groups?.key;
|
|
334
|
+
if (!key) continue;
|
|
335
|
+
const end = (m.index ?? 0) + m[0].length;
|
|
336
|
+
const after = text.slice(end, end + 40);
|
|
337
|
+
const def = m.groups?.def;
|
|
338
|
+
const optional =
|
|
339
|
+
Boolean(p.optional) || (def !== undefined && /^:?[-+]/.test(def)) || (p.call === true && CALL_DEFAULT.test(after)) || (p.member === true && MEMBER_DEFAULT.test(after));
|
|
340
|
+
sink.add(key, sink.lineAt(m.index ?? 0), { optional });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Everything envsonar learns from one file.
|
|
347
|
+
*
|
|
348
|
+
* @param {string} text
|
|
349
|
+
* @param {string} file path used to pick the language
|
|
350
|
+
*/
|
|
351
|
+
export function extractFile(text, file) {
|
|
352
|
+
/** @type {Map<string, Found>} */
|
|
353
|
+
const found = new Map();
|
|
354
|
+
/** @type {{ key: string, line: number }[]} */
|
|
355
|
+
const sections = [];
|
|
356
|
+
/** @type {{ expr: string, line: number }[]} */
|
|
357
|
+
const dynamic = [];
|
|
358
|
+
/** @type {{ key: string, source: string }[]} */
|
|
359
|
+
const provided = [];
|
|
360
|
+
/** @type {Set<string>} */
|
|
361
|
+
const markers = new Set();
|
|
362
|
+
const langs = LANGUAGES.filter((l) => l.test(file));
|
|
363
|
+
if (langs.length) {
|
|
364
|
+
/** @type {Sink} */
|
|
365
|
+
const sink = {
|
|
366
|
+
add(key, line, flags = {}) {
|
|
367
|
+
const id = `${key}:${line}`;
|
|
368
|
+
if (found.has(id)) return;
|
|
369
|
+
found.set(id, { key, line, ...(flags.optional ? { optional: true } : {}), ...(flags.ci ? { ci: true } : {}) });
|
|
370
|
+
},
|
|
371
|
+
section: (key, line) => sections.push({ key, line }),
|
|
372
|
+
dynamic: (expr, line) => dynamic.push({ expr, line }),
|
|
373
|
+
provide: (key, source) => provided.push({ key, source }),
|
|
374
|
+
mark: (marker) => markers.add(marker),
|
|
375
|
+
lineAt: lineIndex(text),
|
|
376
|
+
};
|
|
377
|
+
for (const lang of langs) {
|
|
378
|
+
applyPatterns(text, lang.patterns, sink);
|
|
379
|
+
lang.extra?.(text, sink, file);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return { found: [...found.values()].sort((a, b) => a.line - b.line), sections, dynamic, provided, markers };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Every statically named environment variable read in one file.
|
|
387
|
+
*
|
|
388
|
+
* @param {string} text
|
|
389
|
+
* @param {string} file used to pick the language
|
|
390
|
+
* @returns {Found[]}
|
|
391
|
+
*/
|
|
392
|
+
export function extractKeys(text, file) {
|
|
393
|
+
return extractFile(text, file).found;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Walks `root`: collects every environment variable the code reads, plus what frameworks,
|
|
398
|
+
* SDKs, compose files and appsettings.json provide or read on their own.
|
|
399
|
+
*
|
|
400
|
+
* @param {string} root
|
|
401
|
+
* @param {{ ignoreDirs?: string[], ignoreKeys?: string[] }} [options]
|
|
402
|
+
* @returns {ScanResult}
|
|
403
|
+
*/
|
|
404
|
+
export function scanProject(root, options = {}) {
|
|
405
|
+
const ignoreDirs = new Set([...DEFAULT_IGNORE_DIRS, ...gitignoredDirs(root), ...(options.ignoreDirs ?? [])]);
|
|
406
|
+
const ignored = keyMatcher([...DEFAULT_IGNORE_KEYS, ...(options.ignoreKeys ?? [])]);
|
|
407
|
+
/** @type {ScanResult} */
|
|
408
|
+
const result = { files: 0, usages: new Map(), sections: new Map(), dynamic: [], provided: new Map(), implicit: [] };
|
|
409
|
+
/** @type {Set<string>} */
|
|
410
|
+
const markers = new Set();
|
|
411
|
+
|
|
412
|
+
/** @param {Map<string, Usage[]>} map @param {string} key @param {Usage} usage */
|
|
413
|
+
const push = (map, key, usage) => {
|
|
414
|
+
const list = map.get(key) ?? [];
|
|
415
|
+
if (!list.some((u) => u.file === usage.file && u.line === usage.line)) list.push(usage);
|
|
416
|
+
map.set(key, list);
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
/** @param {string} dir */
|
|
420
|
+
const walk = (dir) => {
|
|
421
|
+
let entries;
|
|
422
|
+
try {
|
|
423
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
424
|
+
} catch {
|
|
425
|
+
return; // unreadable directory: skip it rather than fail the whole scan
|
|
426
|
+
}
|
|
427
|
+
for (const entry of entries) {
|
|
428
|
+
const full = join(dir, entry.name);
|
|
429
|
+
if (entry.isDirectory()) {
|
|
430
|
+
if (!ignoreDirs.has(entry.name) && !existsSync(join(full, "pyvenv.cfg"))) walk(full);
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
if (!entry.isFile()) continue;
|
|
434
|
+
const rel = relative(root, full).split(sep).join("/");
|
|
435
|
+
readManifest(entry.name, full, rel, markers, result.provided);
|
|
436
|
+
if (entry.name.includes(".min.") || !LANGUAGES.some((l) => l.test(entry.name))) continue;
|
|
437
|
+
if (statSync(full).size > MAX_FILE_BYTES) continue;
|
|
438
|
+
result.files++;
|
|
439
|
+
const r = extractFile(readFileSync(full, "utf8"), rel);
|
|
440
|
+
for (const { key, line, ...flags } of r.found) if (!ignored(key)) push(result.usages, key, { file: rel, line, ...flags });
|
|
441
|
+
for (const { key, line } of r.sections) push(result.sections, key, { file: rel, line });
|
|
442
|
+
for (const { expr, line } of r.dynamic) result.dynamic.push({ file: rel, line, expr });
|
|
443
|
+
for (const { key, source } of r.provided) result.provided.set(key.toLowerCase(), { key, source });
|
|
444
|
+
for (const m of r.markers) markers.add(m);
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
walk(root);
|
|
448
|
+
|
|
449
|
+
const all = [...markers];
|
|
450
|
+
for (const profile of PROFILES) {
|
|
451
|
+
const hit = keyMatcher(profile.markers);
|
|
452
|
+
if (all.some(hit)) result.implicit.push({ source: profile.source, keys: profile.keys });
|
|
453
|
+
}
|
|
454
|
+
return result;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Dependency manifests tell which SDKs are in use; appsettings.json provides .NET config values.
|
|
459
|
+
* A manifest that can't be parsed is skipped: it only refines the result.
|
|
460
|
+
*
|
|
461
|
+
* @param {string} name
|
|
462
|
+
* @param {string} full
|
|
463
|
+
* @param {string} rel
|
|
464
|
+
* @param {Set<string>} markers
|
|
465
|
+
* @param {Map<string, { key: string, source: string }>} provided
|
|
466
|
+
*/
|
|
467
|
+
function readManifest(name, full, rel, markers, provided) {
|
|
468
|
+
const lower = name.toLowerCase();
|
|
469
|
+
const isManifest =
|
|
470
|
+
lower === "package.json" || lower === "composer.json" || lower === "pyproject.toml" || lower === "pipfile" ||
|
|
471
|
+
/^requirements.*\.txt$/.test(lower) || /\.(?:cs|fs|vb)proj$/.test(lower) || /^appsettings(?:\.[\w-]+)?\.json$/.test(lower);
|
|
472
|
+
if (!isManifest) return;
|
|
473
|
+
let text;
|
|
474
|
+
try {
|
|
475
|
+
text = readFileSync(full, "utf8");
|
|
476
|
+
} catch {
|
|
477
|
+
return; // unreadable manifest: the code scan still works without it
|
|
478
|
+
}
|
|
479
|
+
if (lower === "package.json" || lower === "composer.json") {
|
|
480
|
+
const json = parseJson(text);
|
|
481
|
+
const kind = lower === "package.json" ? "npm" : "composer";
|
|
482
|
+
for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies", "require", "require-dev"]) {
|
|
483
|
+
for (const dep of Object.keys(json?.[field] ?? {})) markers.add(`${kind}:${dep}`);
|
|
484
|
+
}
|
|
485
|
+
} else if (/\.(?:cs|fs|vb)proj$/.test(lower)) {
|
|
486
|
+
markers.add("dotnet");
|
|
487
|
+
for (const m of text.matchAll(/<PackageReference\s+Include="([^"]+)"/g)) markers.add(`nuget:${m[1]}`);
|
|
488
|
+
} else if (lower.startsWith("appsettings")) {
|
|
489
|
+
/** @type {string[]} */
|
|
490
|
+
const keys = [];
|
|
491
|
+
flatten(parseJson(text.replace(/^\s*\/\/.*$/gm, "")), "", keys);
|
|
492
|
+
for (const key of keys) provided.set(key.toLowerCase(), { key, source: rel });
|
|
493
|
+
} else {
|
|
494
|
+
for (const dep of pythonDeps(text)) markers.add(`py:${dep}`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** @param {string} text @returns {any} */
|
|
499
|
+
function parseJson(text) {
|
|
500
|
+
try {
|
|
501
|
+
return JSON.parse(text.replace(/^/, ""));
|
|
502
|
+
} catch {
|
|
503
|
+
return null; // not valid JSON (or JSON with comments we can't strip): treat as empty
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** @param {unknown} value @param {string} prefix @param {string[]} out */
|
|
508
|
+
function flatten(value, prefix, out) {
|
|
509
|
+
if (value && typeof value === "object") {
|
|
510
|
+
for (const [k, v] of Object.entries(value)) flatten(v, prefix ? `${prefix}__${k}` : k, out);
|
|
511
|
+
} else if (prefix && value !== null && value !== "") {
|
|
512
|
+
out.push(prefix);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** @param {string} text */
|
|
517
|
+
function pythonDeps(text) {
|
|
518
|
+
/** @type {Set<string>} */
|
|
519
|
+
const names = new Set();
|
|
520
|
+
for (const m of text.matchAll(/^[ \t]*([A-Za-z0-9][A-Za-z0-9._-]*)/gm)) names.add(m[1]);
|
|
521
|
+
for (const m of text.matchAll(/["']([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;@][^"']*)?["']/g)) names.add(m[1]);
|
|
522
|
+
return [...names].map((n) => n.toLowerCase().replace(/[._]/g, "-"));
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Plain directory names listed in the root .gitignore (`dist/`, `/storage`); glob patterns are left alone.
|
|
527
|
+
*
|
|
528
|
+
* @param {string} root
|
|
529
|
+
*/
|
|
530
|
+
function gitignoredDirs(root) {
|
|
531
|
+
let text;
|
|
532
|
+
try {
|
|
533
|
+
text = readFileSync(join(root, ".gitignore"), "utf8");
|
|
534
|
+
} catch {
|
|
535
|
+
return []; // no .gitignore
|
|
536
|
+
}
|
|
537
|
+
return text
|
|
538
|
+
.split(/\r?\n/)
|
|
539
|
+
.map((l) => l.trim().replace(/^\//, "").replace(/\/$/, ""))
|
|
540
|
+
.filter((l) => l && !l.startsWith("#") && !l.startsWith("!") && /^[\w.-]+$/.test(l) && !l.startsWith(".env"));
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** @param {string} text */
|
|
544
|
+
function lineIndex(text) {
|
|
545
|
+
const starts = [0];
|
|
546
|
+
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);
|
|
547
|
+
return (/** @type {number} */ offset) => {
|
|
548
|
+
let lo = 0;
|
|
549
|
+
let hi = starts.length - 1;
|
|
550
|
+
while (lo < hi) {
|
|
551
|
+
const mid = (lo + hi + 1) >> 1;
|
|
552
|
+
if (starts[mid] <= offset) lo = mid;
|
|
553
|
+
else hi = mid - 1;
|
|
554
|
+
}
|
|
555
|
+
return lo + 1;
|
|
556
|
+
};
|
|
557
|
+
}
|