vigievuln 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # Changelog — VigieVuln
2
2
 
3
- ## [1.1.1] — Unreleased
3
+ ## [1.1.2] — Unreleased
4
+
5
+ - Fix Windows account sessions when the home directory uses an 8.3 short path, including GitHub Actions temporary directories.
6
+ - Require explicit `--config` for repository configuration and bound Composer validation and JAR decompression.
7
+ - Reject cache archives containing links and keep Python requirements includes inside the scan root.
8
+ - Harden local proxy access and surface failed data sources as incomplete coverage.
9
+
10
+ ## [1.1.1] — 2026-10-28
4
11
 
5
12
  - Review and explicitly accept the current service terms when a hosted account requires it.
6
13
  - Refuse project descriptors larger than 500,000 UTF-8 bytes before upload.
package/README.md CHANGED
@@ -50,8 +50,9 @@ The npm package and primary command are now `vigievuln`. Existing `fad` and
50
50
  The separate shared proxy cache similarly migrates from `~/.fad-checker-proxy-cache/` to `~/.vigie-vuln-proxy-cache/` without merging or overwriting an existing new directory. If either rename fails, the CLI warns you, preserves the old directory and uses a new one. Existing cache archives made with `.fad-checker` remain importable.
51
51
 
52
52
  To recover a failed migration, stop the CLI and proxy server, back up and move the new directory out of the way, then rename the old directory to the new name. Remove the corresponding sibling marker, `~/.vigie-vuln.migration-pending` or `~/.vigie-vuln-proxy-cache.migration-pending`, after recovery. Do not overwrite or merge the directories. While both the marker and old directory exist, the warning repeats once per process; if the marker could not be created, only the immediate warning is assured.
53
- `VIGIEVULN_ENV` and `.vigievuln-env.json` take precedence over their legacy
54
- `FAD_CHECKER_ENV` / `.fad-env.json` counterparts. Default report output is now
53
+ `VIGIEVULN_ENV` takes precedence over the legacy `FAD_CHECKER_ENV`. Project
54
+ configuration is loaded only when explicitly selected with `--config` and must be trusted.
55
+ Default report output is now
55
56
  `./vigievuln-report`; pass `-o` to retain another location.
56
57
 
57
58
  ## Quick start
@@ -304,9 +304,12 @@ public static class VigieVulnSession {
304
304
  static object Execute(Dictionary<string, object> request) {
305
305
  string operation = (string)request["operation"], home = (string)request["homeDir"];
306
306
  if (operation != "read" && operation != "write" && operation != "clear") IO();
307
- // Reject UNC/device paths, alternate streams and DOS path aliases.
307
+ // Reject UNC/device paths and alternate streams. Windows may supply an
308
+ // 8.3 short path (notably TEMP on GitHub runners); expand it before
309
+ // checking every component and the private directory by handle.
308
310
  if (!System.Text.RegularExpressions.Regex.IsMatch(home, @"^[A-Za-z]:\\") || home.IndexOf(':', 2) >= 0 ||
309
- home.IndexOf('/') >= 0 || home.IndexOf('\0') >= 0 || Path.GetFullPath(home) != home) Unsafe();
311
+ home.IndexOf('/') >= 0 || home.IndexOf('\0') >= 0) Unsafe();
312
+ home = Path.GetFullPath(home);
310
313
  string root = home.Substring(0, 3);
311
314
  uint serial, component, flags;
312
315
  StringBuilder format = new StringBuilder(32);
@@ -286,10 +286,22 @@ async function importCache(srcFile, opts = {}) {
286
286
  if (!fs.existsSync(abs)) throw new Error(`archive not found: ${abs}`);
287
287
 
288
288
  // Merge: unpack beside the cache (same filesystem), reconcile, drop the staging dir.
289
- const staging = `${FAD_CACHE_DIR}.import-${process.pid}-${Date.now()}`;
289
+ fs.mkdirSync(path.dirname(FAD_CACHE_DIR), { recursive: true });
290
+ const staging = fs.mkdtempSync(`${FAD_CACHE_DIR}.import-`);
290
291
  const stats = { added: 0, updated: 0, merged: 0, kept: 0, skipped: [] };
291
292
  try {
292
293
  await extractTo(abs, staging, verbose);
294
+ // Never promote links or special files into a live cache, including in
295
+ // replace mode. A later cache write could otherwise escape the cache root.
296
+ const inspect = dir => {
297
+ for (const entry of fs.readdirSync(dir)) {
298
+ const file = path.join(dir, entry), st = fs.lstatSync(file);
299
+ if (st.isSymbolicLink() || (!st.isDirectory() && (!st.isFile() || st.nlink !== 1)))
300
+ throw new Error("archive contains links or special files");
301
+ if (st.isDirectory()) inspect(file);
302
+ }
303
+ };
304
+ inspect(staging);
293
305
  const modern = path.join(staging, path.basename(FAD_CACHE_DIR));
294
306
  const legacy = path.join(staging, '.fad-checker');
295
307
  // Windows Compress-Archive historically emitted the cache contents at
@@ -300,6 +312,18 @@ async function importCache(srcFile, opts = {}) {
300
312
  throw new Error(`archive holds no .vigie-vuln/ or .fad-checker/ directory — was it built with vigievuln --export-cache?`);
301
313
  }
302
314
  if (replace) {
315
+ // Configuration contains machine-local credentials and is never
316
+ // accepted from an imported archive, even for a replacement.
317
+ for (const name of NEVER_IMPORT) {
318
+ const src = path.join(FAD_CACHE_DIR, name), dst = path.join(incoming, name);
319
+ fs.rmSync(dst, { force: true });
320
+ if (fs.existsSync(src)) {
321
+ const st = fs.lstatSync(src);
322
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) throw new Error('unsafe local cache configuration');
323
+ fs.copyFileSync(src, dst, fs.constants.COPYFILE_EXCL);
324
+ try { fs.chmodSync(dst, 0o600); } catch { /* platform does not support chmod */ }
325
+ }
326
+ }
303
327
  if (fs.existsSync(FAD_CACHE_DIR) && !force) {
304
328
  const backup = `${FAD_CACHE_DIR}.bak-${Date.now()}`;
305
329
  fs.renameSync(FAD_CACHE_DIR, backup);
@@ -74,6 +74,7 @@ function composerV2ToPackageObject(json, name) {
74
74
  // public Packagist rich API (packages/<name>.json). Per-registry Basic/Bearer auth.
75
75
  async function fetchPackage(name, { offline, registries = [], fetcher = globalThis.fetch } = {}) {
76
76
  if (offline) return null;
77
+ if (typeof name !== 'string' || name.length > 200 || !/^[a-z0-9]+(?:[_.-][a-z0-9]+)*\/[a-z0-9]+(?:(?:[_.]|-{1,2})[a-z0-9]+)*$/i.test(name)) return { error: 'invalid package name', absent: false };
77
78
  let lastErr = null;
78
79
  const statuses = []; // one per base: HTTP status, or null for a non-answer
79
80
  for (const base of registries || []) {
@@ -81,7 +82,7 @@ async function fetchPackage(name, { offline, registries = [], fetcher = globalTh
81
82
  const ah = authHeaderFor(base); if (ah) headers.Authorization = ah;
82
83
  try {
83
84
  const res = await require("../../providers").getResource("packagist", "p2", { name },
84
- { fetcher, headers, urlOverride: `${normalise(base.url)}p2/${name}.json`, direct: true });
85
+ { fetcher, headers, urlOverride: `${normalise(base.url)}p2/${String(name).split('/').map(encodeURIComponent).join('/')}.json`, direct: true });
85
86
  if (res.ok) return composerV2ToPackageObject(await res.json(), name);
86
87
  lastErr = `HTTP ${res.status}`;
87
88
  statuses.push(res.status);
@@ -24,13 +24,16 @@
24
24
  */
25
25
  const fs = require("fs");
26
26
  const path = require("path");
27
- const { unzipSync, inflateSync, strFromU8 } = require("fflate");
27
+ const { strFromU8 } = require("fflate");
28
+ const { inflateRawSync } = require("node:zlib");
28
29
  const { makeDepRecord } = require("../../dep-record");
29
30
 
30
31
  const ARCHIVE_RE = /\.(jar|war|ear)$/i;
31
32
  const SKIP_DIRS = new Set(["node_modules", ".git", "target", "build", "out", "dist-newstyle", ".gradle", ".m2"]);
32
33
  // A fat-jar can be large; cap what we read into memory and how deep we recurse.
33
34
  const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
35
+ const MAX_ENTRY_BYTES = 64 * 1024 * 1024;
36
+ const MAX_EXPANDED_BYTES = 128 * 1024 * 1024;
34
37
  const MAX_DEPTH = 8;
35
38
 
36
39
  // The ONLY entries we ever decompress out of an archive: its own Maven coordinate
@@ -93,7 +96,7 @@ function coordFromFilename(fileName) {
93
96
  /** Read the named entries from an in-memory zip buffer. Returns {} on a corrupt zip. */
94
97
  function readEntries(buf, filter) {
95
98
  try {
96
- return unzipSync(buf, filter ? { filter: f => filter(f.name) } : undefined);
99
+ return readZipEntriesFromFd(buf, buf.length, filter || (() => true));
97
100
  } catch {
98
101
  return null; // not a valid zip / unsupported (e.g. ZIP64 edge) — caller warns
99
102
  }
@@ -118,9 +121,14 @@ const LOC_SIG = 0x04034b50; // local file header
118
121
  * @returns {Object<string, Uint8Array>} matched entries, same shape as readEntries()
119
122
  */
120
123
  function readZipEntriesFromFd(fd, fileSize, filter) {
124
+ const read = (buffer, length, offset) => {
125
+ if (offset < 0 || length < 0 || offset + length > fileSize) throw new Error('truncated ZIP');
126
+ if (Buffer.isBuffer(fd)) fd.copy(buffer, 0, offset, offset + length);
127
+ else if (fs.readSync(fd, buffer, 0, length, offset) !== length) throw new Error('truncated ZIP');
128
+ };
121
129
  const back = Math.min(fileSize, 65557); // max EOCD comment (65535) + 22-byte record
122
130
  const tail = Buffer.allocUnsafe(back);
123
- fs.readSync(fd, tail, 0, back, fileSize - back);
131
+ read(tail, back, fileSize - back);
124
132
  let e = -1;
125
133
  for (let i = tail.length - 22; i >= 0; i--) {
126
134
  if (tail.readUInt32LE(i) === EOCD_SIG) { e = i; break; }
@@ -131,10 +139,11 @@ function readZipEntriesFromFd(fd, fileSize, filter) {
131
139
  const cdOff = tail.readUInt32LE(e + 16);
132
140
  if (count === 0xffff || cdSize === 0xffffffff || cdOff === 0xffffffff) throw new Error("ZIP64");
133
141
 
142
+ if (cdSize > MAX_ENTRY_BYTES || cdOff + cdSize > fileSize) throw new Error('ZIP central directory too large');
134
143
  const cd = Buffer.allocUnsafe(cdSize);
135
- fs.readSync(fd, cd, 0, cdSize, cdOff);
144
+ read(cd, cdSize, cdOff);
136
145
  const out = {};
137
- let p = 0;
146
+ let p = 0, expanded = 0;
138
147
  for (let i = 0; i < count; i++) {
139
148
  if (p + 46 > cd.length || cd.readUInt32LE(p) !== CEN_SIG) throw new Error("bad central record");
140
149
  const flags = cd.readUInt16LE(p + 8);
@@ -150,17 +159,19 @@ function readZipEntriesFromFd(fd, fileSize, filter) {
150
159
  if (!filter(name)) continue;
151
160
  if (flags & 0x1) throw new Error("encrypted entry");
152
161
  if (compSize === 0xffffffff || uncompSize === 0xffffffff || localOff === 0xffffffff) throw new Error("ZIP64 entry");
162
+ if (compSize > MAX_ENTRY_BYTES || uncompSize > MAX_ENTRY_BYTES || (expanded += uncompSize) > MAX_EXPANDED_BYTES) throw new Error('ZIP expanded data too large');
153
163
  // The local header's name/extra lengths can differ from the central record's,
154
164
  // so read it to locate the actual start of the entry's data.
155
165
  const loc = Buffer.allocUnsafe(30);
156
- fs.readSync(fd, loc, 0, 30, localOff);
166
+ read(loc, 30, localOff);
157
167
  if (loc.readUInt32LE(0) !== LOC_SIG) throw new Error("bad local header");
158
168
  const dataOff = localOff + 30 + loc.readUInt16LE(26) + loc.readUInt16LE(28);
159
169
  const comp = compSize > 0 ? Buffer.allocUnsafe(compSize) : Buffer.alloc(0);
160
- if (compSize > 0) fs.readSync(fd, comp, 0, compSize, dataOff);
170
+ if (compSize > 0) read(comp, compSize, dataOff);
161
171
  if (method === 0) out[name] = comp; // stored
162
- else if (method === 8) out[name] = inflateSync(comp, { out: new Uint8Array(uncompSize) }); // deflate
172
+ else if (method === 8) out[name] = inflateRawSync(comp, { maxOutputLength: Math.min(MAX_ENTRY_BYTES, uncompSize + 1) });
163
173
  else throw new Error("compression method " + method);
174
+ if (out[name].length !== uncompSize) throw new Error('ZIP size mismatch');
164
175
  }
165
176
  return out;
166
177
  }
@@ -194,6 +205,11 @@ function coordForArchive(entries, fileName) {
194
205
  * into any nested archives. `ctx` carries { out, warnings, onProgress, scanned }.
195
206
  */
196
207
  function processEntries(entries, displayPath, fileName, ctx, depth) {
208
+ ctx.expandedBytes = (ctx.expandedBytes || 0) + Object.values(entries).reduce((sum, bytes) => sum + bytes.length, 0);
209
+ if (ctx.expandedBytes > MAX_EXPANDED_BYTES) {
210
+ ctx.warnings.push({ type: 'embedded-jar', message: `expanded archive budget exceeded: ${displayPath}` });
211
+ return;
212
+ }
197
213
  const resolved = coordForArchive(entries, fileName);
198
214
  if (resolved) {
199
215
  const { coord } = resolved;
@@ -259,16 +275,8 @@ function scanArchiveFile(abs, displayPath, fileName, ctx) {
259
275
  const entries = readZipEntriesFromFd(fd, size, wantedEntry);
260
276
  processEntries(entries, displayPath, fileName, ctx, 0);
261
277
  return;
262
- } catch { /* fall back to the whole-buffer path below */ }
278
+ } catch (e) { ctx.warnings.push({ type: "embedded-jar", message: `could not read archive (corrupt, oversized or unsupported): ${displayPath}` }); return; }
263
279
  finally { if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* ignore */ } } }
264
-
265
- // Fallback: read the whole file + fflate (handles ZIP64 etc.).
266
- let buf;
267
- try { buf = fs.readFileSync(abs); }
268
- catch (e) { ctx.warnings.push({ type: "embedded-jar", message: `could not read ${abs}: ${e.message}` }); return; }
269
- const entries = readEntries(buf, wantedEntry);
270
- if (entries === null) { ctx.warnings.push({ type: "embedded-jar", message: `could not read archive (corrupt/unsupported): ${displayPath}` }); return; }
271
- processEntries(entries, displayPath, fileName, ctx, 0);
272
280
  }
273
281
 
274
282
  /** Recursively list archive file paths under `dir`. */
@@ -111,7 +111,8 @@ async function fetchRegistration(name, { offline, version = null, registries = [
111
111
  catch (e) { lastErr = e.message; statuses.push(null); continue; }
112
112
  if (!regBase) { lastErr = "no registration base"; statuses.push(null); continue; }
113
113
  try {
114
- const url = `${regBase}${id}/index.json`;
114
+ if (!/^[a-z0-9_.-]+$/i.test(id) || id === '.' || id === '..') throw new Error('invalid NuGet package name');
115
+ const url = `${regBase}${encodeURIComponent(id)}/index.json`;
115
116
  const res = await require("../../providers").getResource("nuget", "registration", { name: id },
116
117
  { fetcher, headers, ...(url === `https://api.nuget.org/v3/registration5-gz-semver2/${id}/index.json`
117
118
  ? {} : { urlOverride: url, direct: true }) });
@@ -123,13 +123,20 @@ function parsePyprojectToml(filePath) {
123
123
  // Walk a requirements.txt graph, following -r/--requirement (deps) and
124
124
  // -c/--constraint (version pins) includes recursively. `kind` is "req" for the
125
125
  // dependency graph and "constraint" for files reached via -c.
126
- function collectReqGraph(filePath, seen, kind, acc) {
126
+ function collectReqGraph(filePath, seen, kind, acc, root) {
127
127
  const real = path.resolve(filePath);
128
- if (seen.has(real)) return; // cycle / re-include guard
129
- seen.add(real);
128
+ let resolved;
129
+ try { resolved = fs.realpathSync(real); }
130
+ catch { acc.missing.push(real); return; }
131
+ const relative = path.relative(root, resolved);
132
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
133
+ acc.missing.push(`${real} (outside scan root; ignored)`); return;
134
+ }
135
+ if (seen.has(resolved)) return; // cycle / re-include guard
136
+ seen.add(resolved);
130
137
  if (seen.size > 200) return; // sanity bound
131
138
  let lines;
132
- try { lines = fs.readFileSync(real, "utf8").split(/\r?\n/); }
139
+ try { lines = fs.readFileSync(resolved, "utf8").split(/\r?\n/); }
133
140
  catch { acc.missing.push(real); return; }
134
141
  const dir = path.dirname(real);
135
142
  for (const raw of lines) {
@@ -141,9 +148,9 @@ function collectReqGraph(filePath, seen, kind, acc) {
141
148
  line = line.replace(/\\$/, "").trim();
142
149
  if (!line) continue;
143
150
  const rMatch = line.match(/^(?:-r|--requirement)[=\s]+(.+)$/);
144
- if (rMatch) { collectReqGraph(path.resolve(dir, rMatch[1].trim()), seen, kind, acc); continue; }
151
+ if (rMatch) { collectReqGraph(path.resolve(dir, rMatch[1].trim()), seen, kind, acc, root); continue; }
145
152
  const cMatch = line.match(/^(?:-c|--constraint)[=\s]+(.+)$/);
146
- if (cMatch) { collectReqGraph(path.resolve(dir, cMatch[1].trim()), seen, "constraint", acc); continue; }
153
+ if (cMatch) { collectReqGraph(path.resolve(dir, cMatch[1].trim()), seen, "constraint", acc, root); continue; }
147
154
  if (line.startsWith("-")) continue; // -e ., --hash, other flags
148
155
  // Per-requirement options ("pkg==1.0 --hash=sha256:…") come after the spec.
149
156
  const { name, spec } = splitPep508(line.split(/\s+--/)[0].trim());
@@ -154,9 +161,9 @@ function collectReqGraph(filePath, seen, kind, acc) {
154
161
  }
155
162
  }
156
163
 
157
- function parseRequirementsTxt(filePath) {
164
+ function parseRequirementsTxt(filePath, scanRoot = path.dirname(filePath)) {
158
165
  const acc = { reqs: [], constraints: new Map(), missing: [] };
159
- collectReqGraph(filePath, new Set(), "req", acc);
166
+ collectReqGraph(filePath, new Set(), "req", acc, fs.realpathSync(scanRoot));
160
167
  const deps = [];
161
168
  let skipped = 0;
162
169
  const seen = new Set();
@@ -60,11 +60,12 @@ function pypiToFindings(data, { version }) {
60
60
  // Custom registries first (same JSON API: <base>/<name>/json), then pypi.org.
61
61
  async function fetchProject(name, { offline, registries = [], fetcher = globalThis.fetch } = {}) {
62
62
  if (offline) return null;
63
+ if (typeof name !== 'string' || !/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(name)) return { error: 'invalid package name', absent: false };
63
64
  const bases = withPublic("pypi", registries);
64
65
  let lastErr = null;
65
66
  const statuses = []; // one per base: HTTP status, or null for a non-answer
66
67
  for (const base of bases) {
67
- const url = normalise(base.url) + `${name}/json`;
68
+ const url = normalise(base.url) + `${encodeURIComponent(name)}/json`;
68
69
  const headers = { "User-Agent": "vigievuln-pypi", Accept: "application/json" };
69
70
  const ah = authHeaderFor(base); if (ah) headers.Authorization = ah;
70
71
  try { const res = await require("../../providers").getResource("pypi", "package", { name },
@@ -105,7 +105,7 @@ module.exports = {
105
105
  parsedManifests.push(fp);
106
106
  const devFile = DEV_REQ_RE.test(rf);
107
107
  try {
108
- const r = P.parseRequirementsTxt(fp);
108
+ const r = P.parseRequirementsTxt(fp, dir);
109
109
  for (const d of r.deps) add(devFile ? { ...d, isDev: true, scope: "dev" } : d, fp);
110
110
  skipped += r.skipped;
111
111
  sources.push(rf);
package/lib/cve-report.js CHANGED
@@ -1980,9 +1980,11 @@ function renderRetireTable(matches) {
1980
1980
  const isRealIdentifier = id => /^(CVE-|GHSA-|RETIRE-)/i.test(String(id || ""));
1981
1981
  const proseLabel = id => { const s = String(id || "?"); return s.length > 100 ? s.slice(0, 100) + "…" : s; };
1982
1982
  const idLink = m => {
1983
- const href = m.cve.id?.startsWith("CVE-")
1983
+ const candidate = m.cve.id?.startsWith("CVE-")
1984
1984
  ? `https://nvd.nist.gov/vuln/detail/${esc(m.cve.id)}`
1985
1985
  : (m.cve.osvRefs?.[0]?.url || null);
1986
+ let href = null;
1987
+ try { if (candidate && ['https:', 'http:'].includes(new URL(candidate).protocol)) href = candidate; } catch { /* untrusted advisory URL */ }
1986
1988
  const real = isRealIdentifier(m.cve.id);
1987
1989
  const chop = real ? " no-chop" : "";
1988
1990
  const label = esc(real ? m.cve.id : proseLabel(m.cve.id));
package/lib/kev.js CHANGED
@@ -89,7 +89,10 @@ async function enrichKev(matches, opts = {}) {
89
89
  if (verbose) console.warn(` KEV fetch failed: ${err.message}`);
90
90
  }
91
91
  }
92
- if (!index) return matches;
92
+ if (!index) {
93
+ if (!offline) throw new Error('CISA KEV catalog unavailable; exploitation status is unknown');
94
+ return matches;
95
+ }
93
96
 
94
97
  for (const m of matches || []) {
95
98
  const hit = index.byId[m.cve?.id];
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * lib/options-env.js — layered option resolution.
3
3
  *
4
- * Layers (highest → lowest): CLI flags > config file (--config / ./.fad-env.json,
4
+ * Layers (highest → lowest): CLI flags > explicitly selected config file (--config,
5
5
  * JSON) > FAD_CHECKER_ENV (a CLI-flag string) > global ~/.fad-checker/config.json
6
6
  * > commander defaults. Scalar options follow precedence; `registries` are unioned
7
7
  * elsewhere (lib/registries.js). The source flag has aliases (src/source).
@@ -69,10 +69,9 @@ function parseEnvFlags(str, program) {
69
69
  /** Resolve { fileLayer, envLayer, envRepos }. */
70
70
  function loadLayers({ cwd = process.cwd(), configPath = null, envStr = process.env.VIGIEVULN_ENV ?? process.env.FAD_CHECKER_ENV, program = null } = {}) {
71
71
  let fileLayer = {};
72
- const modern = path.join(cwd, ".vigievuln-env.json");
73
- const chosen = configPath || (fs.existsSync(modern) ? modern : path.join(cwd, ".fad-env.json"));
74
- if (configPath) fileLayer = loadConfigFile(chosen);
75
- else if (fs.existsSync(chosen)) fileLayer = loadConfigFile(chosen);
72
+ // The working directory may be the untrusted repository being audited.
73
+ // Only an explicitly selected configuration may affect the scan.
74
+ if (configPath) fileLayer = loadConfigFile(configPath);
76
75
  fileLayer = normalizeSource(fileLayer || {});
77
76
  let envLayer = {}, envRepos = [];
78
77
  if (envStr && program) {
@@ -45,13 +45,15 @@ const STABILITY_ALIAS = { a: "alpha", alpha: "alpha", b: "beta", beta: "beta", r
45
45
  // VersionParser's classical version + modifier regex (any number of numeric parts —
46
46
  // Composer stops at 4, but a longer one was accepted before and is still ordered sanely),
47
47
  // optional build metadata ignored like Composer does.
48
- const VERSION_RE = /^v?(\d+(?:\.\d+)*)(?:[._-]?(stable|beta|b|rc|alpha|a|patch|pl|p)((?:[.-]?\d+)*))?([.-]?dev)?(?:\+\S+)?$/i;
48
+ const VERSION_RE = /^v?(\d+(?:\.\d+)*)(?:[._-]?(stable|beta|b|rc|alpha|a|patch|pl|p)(\d*(?:[.-]\d+)*))?([.-]?dev)?(?:\+\S+)?$/i;
49
49
 
50
50
  // "1.35.0" → { nums:[1,35,0], stab:"stable", stabNums:[], dev:false, hasStab:false };
51
51
  // "v1.7.0-beta2" → stab "beta", stabNums [2]; "1.0.0-dev" → stab "dev". Unparsable
52
52
  // (branch "dev-main", "1.0.x-dev", an unknown suffix "1.0.0-foo") → null.
53
53
  function parseComposerVersion(value) {
54
- const m = VERSION_RE.exec(String(value ?? "").trim());
54
+ const input = String(value ?? "").trim();
55
+ if (input.length > 256) return null;
56
+ const m = VERSION_RE.exec(input);
55
57
  if (!m) return null;
56
58
  const word = m[2] ? STABILITY_ALIAS[m[2].toLowerCase()] : null;
57
59
  const dev = !!m[4];
@@ -101,6 +101,15 @@ function createProxyCacheServer(opts = {}) {
101
101
 
102
102
  async function handle(req, res) {
103
103
  stats.requests++;
104
+ // CLI clients do not send an Origin; reject browser requests before any
105
+ // control or resource endpoint can be used for CSRF or DNS rebinding.
106
+ if (req.headers.origin || req.headers['sec-fetch-site']) return sendJson(res, 403, { error: 'browser requests are not supported' });
107
+ const address = server.address();
108
+ if (address && typeof address !== 'string' && ['127.0.0.1', '::1'].includes(address.address)) {
109
+ let hostname;
110
+ try { hostname = new URL(`http://${req.headers.host}`).hostname.toLowerCase(); } catch { return sendJson(res, 400, { error: 'invalid host' }); }
111
+ if (!['127.0.0.1', '[::1]', 'localhost'].includes(hostname)) return sendJson(res, 403, { error: 'invalid host' });
112
+ }
104
113
  const target = req.url.replace(/^\/+/, "");
105
114
  if (target === "__health") return sendJson(res, 200, { ok: true, uptimeMs: Date.now() - stats.startedAt });
106
115
  if (!authorized(req)) return sendJson(res, 401, { error: "unauthorized", "x-fad-proxy": "unauthorized" });
@@ -126,7 +135,7 @@ function createProxyCacheServer(opts = {}) {
126
135
  const server = http.createServer((req, res) => {
127
136
  handle(req, res).catch(err => {
128
137
  stats.errors++;
129
- if (!res.headersSent) sendJson(res, 502, { error: String(err.message || err) }, { "x-fad-proxy": "error" });
138
+ if (!res.headersSent) sendJson(res, 502, { error: "upstream request failed" }, { "x-fad-proxy": "error" });
130
139
  else res.destroy();
131
140
  });
132
141
  });
@@ -146,6 +155,7 @@ function createProxyCacheServer(opts = {}) {
146
155
  /** Convenience: create + listen. Resolves { server, url, port } once the socket is open. */
147
156
  function startProxyCacheServer(opts = {}) {
148
157
  const { port = DEFAULT_PORT, host = DEFAULT_HOST } = opts;
158
+ if (!['127.0.0.1', '::1', 'localhost'].includes(host) && !opts.token) throw new Error('a token is required when serve-cache is exposed beyond localhost');
149
159
  const server = createProxyCacheServer(opts);
150
160
  return new Promise((resolve, reject) => {
151
161
  server.once("error", reject);
@@ -51,7 +51,9 @@ const T = {
51
51
 
52
52
  const CVE = T.str(/^CVE-\d{4}-\d{4,7}$/i, 20);
53
53
  const NAME = T.str(/^[A-Za-z0-9@][A-Za-z0-9._~\/@+-]*$/, 214);
54
- const COMPOSER = T.str(/^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$/i, 200);
54
+ // Separators are mandatory between runs: the old optional separator nested
55
+ // inside a repetition allowed exponentially many partitions of a long name.
56
+ const COMPOSER = T.str(/^[a-z0-9]+(?:[_.-][a-z0-9]+)*\/[a-z0-9]+(?:(?:[_.]|-{1,2})[a-z0-9]+)*$/i, 200);
55
57
  const OSV_ECOS = ["Maven", "npm", "PyPI", "Packagist", "NuGet", "Go", "RubyGems", "crates.io", "Hex", "Pub", "CRAN", "Hackage", "SwiftURL", "GitHub Actions"];
56
58
  const OSV_NAME = T.str(/^[\x21-\x7e]+$/, 300), OSV_VERSION = T.str(/^[\x21-\x7e]+$/, 100);
57
59
  const OSV_PAGE_TOKEN = T.str(/^[\x21-\x7e]+$/, 2048);
package/lib/retire.js CHANGED
@@ -325,6 +325,8 @@ async function runRetire(srcDir, opts = {}) {
325
325
  const diag = opts.diag || {};
326
326
  // No source tree (e.g. --import-anonymized) → nothing to scan for vendored JS.
327
327
  if (!srcDir) { if (verbose) console.warn("retire: no source dir — skipped"); return null; }
328
+ try { if (!fs.statSync(srcDir).isDirectory()) throw new Error('not a directory'); }
329
+ catch { diag.error = 'retire.js scan failed: source directory is unavailable'; return null; }
328
330
  const hostedOnline = !offline && require("./providers").hasHostedProxy();
329
331
  // A result's scan time cannot prove that the signatures it used are still current.
330
332
  if (!force && !hostedOnline) {
@@ -352,7 +354,8 @@ async function runRetire(srcDir, opts = {}) {
352
354
 
353
355
  // retire.js refuses to write to /dev/stdout, so we use a real temp file
354
356
  // and read it back. Falls back to stdout if --outputpath is rejected.
355
- const tmpOut = path.join(os.tmpdir(), `vigievuln-retire-${process.pid}-${Date.now()}.json`);
357
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vigievuln-retire-'));
358
+ const tmpOut = path.join(tmpDir, 'output.json');
356
359
 
357
360
  // Pruning policy, written to a temp ignorefile so retire honors it for the tree
358
361
  // it ACTUALLY walks (anchored to srcDir, not retire's cwd — the nested
@@ -360,11 +363,11 @@ async function runRetire(srcDir, opts = {}) {
360
363
  const ignorePatterns = buildRetireIgnorePatterns({ srcDir, excludePath, defaultExcludes });
361
364
  // retire treats a `.json` ignorefile as the structured descriptor form; keep a
362
365
  // plain-text extension so the `@`-prefixed regex lines are read as such.
363
- const tmpIgnore = ignorePatterns.length ? path.join(os.tmpdir(), `vigievuln-retire-ignore-${process.pid}-${Date.now()}.txt`) : null;
364
- if (tmpIgnore) fs.writeFileSync(tmpIgnore, ignorePatterns.join("\n") + "\n");
366
+ const tmpIgnore = ignorePatterns.length ? path.join(tmpDir, 'ignore.txt') : null;
367
+ try { if (tmpIgnore) fs.writeFileSync(tmpIgnore, ignorePatterns.join("\n") + "\n", { mode: 0o600, flag: 'wx' }); }
368
+ catch (error) { fs.rmSync(tmpDir, { recursive: true, force: true }); throw error; }
365
369
  const cleanup = () => {
366
- try { fs.unlinkSync(tmpOut); } catch { /* best effort */ }
367
- if (tmpIgnore) { try { fs.unlinkSync(tmpIgnore); } catch { /* best effort */ } }
370
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best effort */ }
368
371
  };
369
372
 
370
373
  const args = buildRetireArgs({ srcDir, outPath: tmpOut, ignoreFile: tmpIgnore, jsRepo: haveSig ? RETIRE_SIG_FILE : null });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vigievuln",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "One-shot polyglot dependency auditor (10 ecosystems + 9 CMS/Frameworks). No build tools. Real & complete air-gapped mode. Private deps, binaries, certs, EOL, CVE (KEV+EPSS) - Made for professional code audits.",
5
5
  "keywords": [
6
6
  "sca",
@@ -95,13 +95,13 @@
95
95
  "js-yaml": "^4.3.2",
96
96
  "minimatch": "^10.2.6",
97
97
  "p-limit": "^3.1.0",
98
- "retire": "^5.7.0",
98
+ "retire": "^6.1.0",
99
99
  "rimraf": "^6.1.3",
100
100
  "smol-toml": "^1.8.0",
101
101
  "xml2js": "^0.6.2"
102
102
  },
103
103
  "engines": {
104
- "node": ">=20"
104
+ "node": "^20.19.0 || >=22.12.0"
105
105
  },
106
106
  "files": [
107
107
  "vigievuln.js",
package/vigievuln.js CHANGED
@@ -374,7 +374,7 @@ if (process.argv[2] === "serve-cache") {
374
374
  })).then(({ server, url }) => {
375
375
  console.log(chalk.green(`✅ proxy-cache listening on ${url}`));
376
376
  console.log(chalk.gray(` store: ${storeDir} (persists across restarts; separate from the scan's own ~/.vigie-vuln/ caches)`));
377
- console.log(chalk.gray(` upstream: ${upstreamProxy ? `via corporate proxy ${upstreamProxy}` : "direct"}`));
377
+ console.log(chalk.gray(` upstream: ${upstreamProxy ? "via corporate proxy" : "direct"}`));
378
378
  console.log(chalk.gray(` stats: ${url}/__stats clear: POST ${url}/__clear`));
379
379
  const active = Object.entries(keys).filter(([, v]) => v).map(([k]) => k);
380
380
  console.log(chalk.gray(` api keys: ${active.length ? active.join(", ") + " (injected upstream; instances behind --proxy-cache need none)" : "none configured (client-sent credentials are forwarded as-is)"}`));
@@ -409,7 +409,7 @@ program
409
409
  // Not a requiredOption: --import-anonymized scans a descriptor with no source tree.
410
410
  .option("-s, --src <src>", "source directory (legacy alternative to scan <dir>)")
411
411
  .option("--source <src>", "alias of --src")
412
- .option("--config <file>", "load default options from JSON (else ./.vigievuln-env.json, then legacy ./.fad-env.json)")
412
+ .option("--config <file>", "load default options from a trusted JSON file")
413
413
  .option("-d, --disable <list>", "turn features OFF (comma-separated) — see the token list below")
414
414
  .option("-a, --activate <list>", "turn ON what is off by default (comma-separated) — see below")
415
415
  .option("-r, --report <list>", "outputs to write, comma-separated: html,doc,xlsx,sbom,csaf,json,sarif (default: html,json)")
@@ -590,7 +590,7 @@ if (BARE_ARGV) {
590
590
  program.parse(process.argv);
591
591
 
592
592
  const options = program.opts();
593
- // Layered config: CLI flags > config file (--config / ./.fad-env.json, JSON) >
593
+ // Layered config: CLI flags > explicitly selected config file (--config, JSON) >
594
594
  // FAD_CHECKER_ENV (a CLI-flag string) > global ~/.vigie-vuln/config.json >
595
595
  // commander defaults. A file/env value fills an option only if the CLI didn't
596
596
  // set it. `registries` are unioned separately (below). Source has src/source aliases.
@@ -613,6 +613,15 @@ if (!options.offline && !options.proxyCacheToken && !process.env.VIGIEVULN_PROXY
613
613
  }
614
614
  try { Object.assign(options, require("./lib/hosted-proxy").resolveHostedProxy({ ...options, allowProxyLogin: !!hostedAccountSession || !!(process.stdin.isTTY && process.stderr.isTTY) })); }
615
615
  catch (err) { console.error(chalk.red(`❌ ${err.message}`)); process.exit(2); }
616
+ // A saved official account key must never follow a changed proxy URL to an
617
+ // unrelated service. Custom proxies require a token supplied for this run.
618
+ if (options.proxyCache && !options.vigievulnProxy && options.proxyCacheToken &&
619
+ !program.getOptionValueSource('proxyCacheToken')?.match(/^(cli|env)$/) &&
620
+ !Object.hasOwn(_layers.fileLayer, 'proxyCacheToken') && !Object.hasOwn(_layers.envLayer, 'proxyCacheToken') &&
621
+ !process.env.VIGIEVULN_PROXY_CACHE_TOKEN && !process.env.FAD_PROXY_CACHE_TOKEN) {
622
+ console.error(chalk.red('❌ A saved proxy key cannot be sent to a custom proxy. Supply its token explicitly for this run.'));
623
+ process.exit(2);
624
+ }
616
625
  // --source CLI alias → src (applyLayers already maps the file/env JSON 'source' key).
617
626
  if (!options.src && options.source) options.src = options.source;
618
627
 
@@ -1585,7 +1594,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1585
1594
  st.done(`${cveMatches.length} match(es)${cveDataDate ? ` · ${String(cveDataDate).slice(0, 10)}` : ""}`);
1586
1595
  } catch (err) {
1587
1596
  st.fail(err.message);
1588
- if (options.vigievulnProxy) scanWarnings.push({type:"source-unavailable",message:`CVEProject: ${err.message}; Maven CVE coverage is incomplete.`});
1597
+ scanWarnings.push({type:"source-unavailable",message:`CVEProject: ${err.message}; Maven CVE coverage is incomplete.`});
1589
1598
  }
1590
1599
  }
1591
1600
 
@@ -1827,7 +1836,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1827
1836
  await enrichEpss(cveMatches, { verbose, offline, onProgress: (p, t) => st.tick(p, t) });
1828
1837
  const scored = cveMatches.filter(m => m.cve?.epssPercentile != null).length;
1829
1838
  st.done(`${scored} scored`);
1830
- } catch (err) { st.fail(err.message); if (options.vigievulnProxy) scanWarnings.push({type:"source-unavailable",message:`EPSS: ${err.message}; enrichment is incomplete.`}); }
1839
+ } catch (err) { st.fail(err.message); scanWarnings.push({type:"source-unavailable",message:`EPSS: ${err.message}; enrichment is incomplete.`}); }
1831
1840
  }
1832
1841
  }
1833
1842
 
@@ -1841,7 +1850,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1841
1850
  await enrichKev(cveMatches, { verbose, offline, hostedProxy: !!options.vigievulnProxy });
1842
1851
  const kevd = cveMatches.filter(m => m.cve?.kev).length;
1843
1852
  st.done(`${kevd} known-exploited`);
1844
- } catch (err) { st.fail(err.message); if (options.vigievulnProxy) scanWarnings.push({type:"source-unavailable",message:`CISA KEV: ${err.message}; exploitation status is incomplete.`}); }
1853
+ } catch (err) { st.fail(err.message); scanWarnings.push({type:"source-unavailable",message:`CISA KEV: ${err.message}; exploitation status is incomplete.`}); }
1845
1854
  }
1846
1855
  }
1847
1856
 
@@ -1862,7 +1871,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1862
1871
  const ids = new Set(cveMatches.filter(m => m.cve?.euvd?.id).map(m => m.cve.id)).size;
1863
1872
  const exploited = new Set(cveMatches.filter(m => m.cve?.euvd?.exploitedSince != null).map(m => m.cve.id)).size;
1864
1873
  st.done(`${ids} EUVD id(s) · ${exploited} exploited per ENISA`);
1865
- } catch (err) { st.fail(err.message); if (options.vigievulnProxy) scanWarnings.push({type:"source-unavailable",message:`EUVD: ${err.message}; enrichment is incomplete.`}); }
1874
+ } catch (err) { st.fail(err.message); scanWarnings.push({type:"source-unavailable",message:`EUVD: ${err.message}; enrichment is incomplete.`}); }
1866
1875
  }
1867
1876
  }
1868
1877
  if (willCertFr) {
@@ -1874,7 +1883,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1874
1883
  await enrichCertFr(cveMatches, { verbose, offline, hostedProxy: !!options.vigievulnProxy, onProgress: (p, t) => st.tick(p, t) });
1875
1884
  const cited = new Set(cveMatches.filter(m => m.cve?.certfr?.length).map(m => m.cve.id)).size;
1876
1885
  st.done(`${cited} CVE(s) cited by CERT-FR`);
1877
- } catch (err) { st.fail(err.message); if (options.vigievulnProxy) scanWarnings.push({type:"source-unavailable",message:`CERT-FR: ${err.message}; enrichment is incomplete.`}); }
1886
+ } catch (err) { st.fail(err.message); scanWarnings.push({type:"source-unavailable",message:`CERT-FR: ${err.message}; enrichment is incomplete.`}); }
1878
1887
  }
1879
1888
  }
1880
1889
 
@@ -2444,7 +2453,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2444
2453
  }
2445
2454
  if (options.failOnIncomplete) {
2446
2455
  const { requiredCoverageComplete } = require("./lib/scan-coverage");
2447
- const raw = options.failOnIncomplete === true ? "inventory,advisories" : String(options.failOnIncomplete);
2456
+ const raw = options.failOnIncomplete === true ? "inventory,advisories,sources" : String(options.failOnIncomplete);
2448
2457
  const required = [...new Set(raw.split(",").map(x => x.trim()).filter(Boolean))];
2449
2458
  const known = new Set(["inventory", "advisories", "recipes", "sources"]);
2450
2459
  if (!required.length || required.some(x => !known.has(x))) {