vigievuln 1.1.2 → 1.1.3

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,5 +1,15 @@
1
1
  # Changelog — VigieVuln
2
2
 
3
+ ## [1.1.3] — 2026-10-29
4
+
5
+ - Reuse fresh proxy-confirmed responses locally for up to one hour, and preserve stale-source warnings when refresh fails.
6
+ - Allow up to 100 hosted proxy requests per second, respecting server rate limits and retry delays.
7
+ - Select the official proxy on login when no proxy is configured; retain an existing proxy selection.
8
+ - Improve hosted scans, report links, account and cache handling, and Maven presence validation.
9
+ - Trim whitespace around Maven versions before OSV lookups so one malformed value cannot reject a whole batch.
10
+ - Refresh the example audit reports and their screenshot.
11
+ - Send the CLI version to the hosted proxy and explain how to update when the server requires a newer version.
12
+
3
13
  ## [1.1.2] — Unreleased
4
14
 
5
15
  - Fix Windows account sessions when the home directory uses an 8.3 short path, including GitHub Actions temporary directories.
package/README.md CHANGED
@@ -10,14 +10,14 @@
10
10
  [![CI](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml/badge.svg)](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml)
11
11
 
12
12
 
13
- **VigieVuln** (formerly `fad-checker`) is a polyglot dependency auditor built for **professional code audits**.
13
+ **VigieVuln** is a polyglot dependency auditor built for **professional code audits**.
14
14
 
15
15
  It scans **10 ecosystems + 9 CMS/Frameworks** (WordPress, Drupal, Symfony, Laravel…) in one pass, with **no build tools**, support **air-gapped** workflows using transferred caches, private package detection, committed binaries & certificates, then produces clean **HTML reports + json baseline + (DOC/XLSX/SARIF/CycloneDX/etc)** .
16
16
 
17
17
 
18
18
  🌐 **[Project site & docs →](https://9pings.github.io/VigieVuln/)**
19
19
 
20
- *Demo and sample reports generated with VigieVuln 1.0.1.*
20
+ *Terminal demo recorded with VigieVuln 1.0.1.*
21
21
 
22
22
  <p align="center"><img src="docs/assets/demo.gif" alt="vigievuln animated terminal demo: an offline Maven audit — dependencies absent from Maven Central flagged as private/internal, the compact single-line vulnerability-database progress, then findings coloured by severity" height="500"></p>
23
23
 
@@ -43,18 +43,6 @@ It scans **10 ecosystems + 9 CMS/Frameworks** (WordPress, Drupal, Symfony, Larav
43
43
 
44
44
  📖 **[Usage & all flags](docs/USAGE.md)** · **[Architecture](docs/ARCHITECTURE.md)** · **[Comparison vs other tools](docs/COMPARISON.md)** · **[Data sources](docs/DATA-SOURCES.md)**
45
45
 
46
- ## Migration from fad-checker
47
-
48
- The npm package and primary command are now `vigievuln`. Existing `fad` and
49
- `fad-checker` commands remain aliases. The default cache and configuration directory is `~/.vigie-vuln/`. If it does not exist, an existing `~/.fad-checker/` is automatically renamed to it. If the new directory already exists, it is kept. If the rename fails, a new directory is created and execution continues; the old directory is not merged.
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
-
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` 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
56
- `./vigievuln-report`; pass `-o` to retain another location.
57
-
58
46
  ## Quick start
59
47
 
60
48
  ```bash
@@ -76,11 +64,9 @@ vigievuln project status
76
64
  vigievuln logout
77
65
  ```
78
66
 
79
- `watch` collects the inventory locally and uploads it once. Run it again with the same unique project name to update that project's inventory; it does not run a background watcher. `login` creates an account session and does not configure the proxy cache.
67
+ `watch` collects the inventory locally and uploads it once. Run it again with the same unique project name to update that project's inventory; it does not run a background watcher. `login` selects the official proxy if none is configured; an existing proxy remains selected.
80
68
 
81
- The free tier includes **one project and up to 100 distinct direct dependency coordinates per project**. Multiple versions of the same coordinate count once. An uploaded descriptor may be at most **500,000 bytes (0.5 MB decimal)**; an upload exceeding this size or 100 distinct direct coordinates is rejected with an error. Dependencies whose direct relationship cannot be established are excluded from monitoring and reported as incomplete coverage. These limits apply to hosted monitoring, not local scans.
82
-
83
- Free monitoring expires **one calendar month (UTC)** after a successful `watch` upload. Each successful upload, including a project API push, renews the period for one calendar month (UTC). At expiry, the hosted project and its monitoring data are purged and an expiry email is sent; the account remains. Copies in backups are not deleted immediately.
69
+ The free tier watches **one project, up to 100 direct dependencies and a 0.5 MB descriptor**, for **one month renewed by each upload**; expiry deletes the monitoring data and triggers an email.
84
70
 
85
71
  If the current terms have not been accepted, the CLI displays their link and asks for explicit acceptance in an interactive terminal. For non-interactive use, run `vigievuln login` interactively and accept the terms first.
86
72
 
@@ -90,18 +76,20 @@ To review the inventory before uploading, export it locally:
90
76
  vigievuln watch ./project --export fichier.json
91
77
  ```
92
78
 
93
- `--export` only writes the descriptor: it runs offline, requires no login, sends nothing to the service and does not renew monitoring. Review package names and versions, including private packages, before uploading. Source code, paths and registry URLs are omitted from the descriptor.
79
+ `--export` writes an offline descriptor without uploading; review package names and versions, including private packages, before sharing it.
94
80
 
95
- Monitoring establishes a silent initial baseline, then reports new high or critical vulnerabilities (CVSS ≥ 7) and known exploited vulnerabilities affecting direct dependencies. Enable alerts in your account and refresh the inventory when dependencies change. [Monitoring workflow and compatibility commands](docs/USAGE.md#project-monitoring).
81
+ Enable alerts in your account to receive new high, critical or known exploited vulnerabilities affecting your direct dependencies; refresh the inventory when dependencies change. [Monitoring guide](docs/USAGE.md#project-monitoring).
96
82
 
97
83
  Existing commands remain supported: `vigievuln -s ./code`, `auth login|status|logout`, `--prepare-project` and `project push`.
98
84
 
99
85
  ### Official Vigie Vuln proxy cache
100
86
 
87
+ [Vigie Vuln DB](https://www.vigievuln.fr/) hosts vulnerability data and the official proxy cache in Europe.
88
+
101
89
  Configure the proxy once, then sign in with your verified [Vigie Vuln account](https://www.vigievuln.fr/account) when prompted:
102
90
 
103
91
  ```bash
104
- vigievuln --set-proxy-cache vigievuln # `default` selects the same official proxy
92
+ vigievuln login # selects the official proxy if none is configured
105
93
  vigievuln scan ./code
106
94
  ```
107
95
 
@@ -109,10 +97,10 @@ The selection and the proxy key created during proxy sign-in are saved in `~/.vi
109
97
 
110
98
  ### Interactive HTML samples
111
99
 
112
- - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below, rescanned with VigieVuln 1.0.1; 105 Maven descriptors, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
100
+ - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below, rescanned with VigieVuln 1.1.3; 105 Maven descriptors, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
113
101
  - **[Multi-instance CMS & frameworks — open the report](https://9pings.github.io/VigieVuln/samples/multi-cms-frameworks.html)**: WordPress 6.4.2, Drupal 8.5.0, Symfony Demo (Symfony 7.1.1) and BookStack v24.10 (Laravel 10.48.22), with findings attributed to each instance.
114
102
 
115
- These are standalone reports from real source scans, generated offline on **2026-10-26** using the local cache. The CMS sample focuses on PHP dependencies; WordPress advisory coverage is explicitly incomplete without a Wordfence feed. [Sample scope, sources and reproduction commands](docs/samples/README.md).
103
+ These are standalone reports from real source scans, generated on **2026-10-29** using the hosted proxy and local caches. The CMS sample focuses on PHP dependencies; WordPress advisory coverage is explicitly incomplete without a Wordfence feed. [Sample scope, sources and reproduction commands](docs/samples/README.md).
116
104
 
117
105
  > [!WARNING]
118
106
  > vigievuln is new and may still contain ( rare ) bugs. Treat its output as a strong first pass, **double-check anything critical**, and please [report issues](https://github.com/9pings/VigieVuln/issues); they get fixed fast.
@@ -252,15 +240,14 @@ vigievuln -s ./proj --offline # re-collect locally (real paths) +
252
240
  # the online phase ride the same archive and are consumed automatically — no flags.
253
241
  ```
254
242
 
255
- Since **fad-checker 2.7.4** (included in VigieVuln 1.0.0), descriptor imports also warm Maven registry presence (unless
243
+ Descriptor imports also warm Maven registry presence (unless
256
244
  `--no-all-libs` is set). Legacy negative presence entries are discarded automatically:
257
245
  older versions could confuse network errors with missing packages. Until verified
258
246
  online, those entries remain **unknown**, including after a cache merge. Other warmed
259
247
  analysis data is retained.
260
248
 
261
- The inherited **fad-checker 2.7.4** release also stops trusting legacy empty OSV cache entries, because an older
262
- failed request could have been stored as “no vulnerabilities”. Re-warm and export the
263
- cache with VigieVuln 1.0.0 to verify these entries; until then offline reports warn about incomplete
249
+ Unverified empty OSV cache entries are not trusted, because a failed request may have
250
+ been stored as “no vulnerabilities”. Re-warm and export the cache to verify these entries; until then offline reports warn about incomplete
264
251
  OSV coverage. Existing cached advisory IDs remain usable. Offline KEV and binary identity
265
252
  lookups reuse the last available snapshot even after 24 hours, without changing its date.
266
253
 
@@ -18,33 +18,35 @@ class AccountClientError extends Error {
18
18
  const invalidResponse = () => new AccountClientError('INVALID_RESPONSE', 'Invalid account API response.');
19
19
  const isAccount = value => value && typeof value === 'object' && !Array.isArray(value) &&
20
20
  typeof value.id === 'string' && value.id.length > 0 && typeof value.email === 'string' && value.email.length > 0;
21
- function readTerms(value) {
21
+ function readTerms(value, origin = ACCOUNT_ORIGIN) {
22
22
  if (!value || typeof value !== 'object' || Array.isArray(value) ||
23
23
  typeof value.version !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(value.version) ||
24
24
  typeof value.documentUrl !== 'string' || value.documentUrl.length > 2048 ||
25
25
  /[\x00-\x20\x7f]/.test(value.documentUrl) || typeof value.accepted !== 'boolean') throw invalidResponse();
26
26
  let url;
27
- try { url = new URL(value.documentUrl, ACCOUNT_ORIGIN); } catch { throw invalidResponse(); }
28
- if (url.protocol !== 'https:' || url.origin !== ACCOUNT_ORIGIN || url.username || url.password ||
27
+ try { url = new URL(value.documentUrl, origin); } catch { throw invalidResponse(); }
28
+ if (url.origin !== origin || url.username || url.password ||
29
29
  url.pathname !== '/terms/' + value.version || url.search || url.hash ||
30
- ![url.pathname, ACCOUNT_ORIGIN + url.pathname].includes(value.documentUrl)) throw invalidResponse();
30
+ ![url.pathname, origin + url.pathname].includes(value.documentUrl)) throw invalidResponse();
31
31
  return { version: value.version, url: url.href, accepted: value.accepted };
32
32
  }
33
33
 
34
34
  /**
35
- * Account authentication for future project commands; no proxy config or keys.
36
- * Only the transport, store, clock and timeout are injectable; never the origin.
35
+ * Account authentication for the official service or an explicitly configured proxy.
36
+ * Sessions are bound to their account origin before any authenticated request.
37
37
  * login({email,password}) -> {account,expiresAt}; me() -> {account};
38
38
  * logout() -> {revoked}. logout always clears local storage, including on a
39
39
  * remote error, which is still reported (revocation is then unconfirmed).
40
40
  * The password exists only in the in-flight request, never in the store.
41
41
  */
42
- function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
42
+ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now, accountOrigin = ACCOUNT_ORIGIN,
43
43
  sessionStore = createAccountSessionStore({ now }), timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
44
44
  if (typeof fetcher !== 'function' || !Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
45
45
  throw new AccountClientError('INVALID_OPTIONS', 'Invalid account transport or timeout.');
46
46
  }
47
47
 
48
+ let parsedOrigin; try { parsedOrigin = new URL(accountOrigin); } catch { throw new AccountClientError('INVALID_OPTIONS', 'Invalid account origin.'); }
49
+ if (parsedOrigin.origin !== accountOrigin || !['https:', 'http:'].includes(parsedOrigin.protocol) || parsedOrigin.username || parsedOrigin.password) throw new AccountClientError('INVALID_OPTIONS', 'Invalid account origin.');
48
50
  async function request(route, method, body, token) {
49
51
  const controller = new AbortController();
50
52
  let timer;
@@ -56,7 +58,7 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
56
58
  }, timeoutMs);
57
59
  });
58
60
  const operation = async () => {
59
- response = await fetcher(ACCOUNT_ORIGIN + '/v1/accounts/' + route, {
61
+ response = await fetcher(accountOrigin + '/v1/accounts/' + route, {
60
62
  method, redirect: 'error', credentials: 'omit', cache: 'no-store',
61
63
  headers: { accept: 'application/json', ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
62
64
  ...(token ? { authorization: 'Bearer ' + token } : {}) },
@@ -68,7 +70,7 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
68
70
  }
69
71
  // Also reject an injected transport that reports a redirect/followed URL.
70
72
  if (response.redirected || (response.status >= 300 && response.status < 400) ||
71
- (response.url && response.url !== ACCOUNT_ORIGIN + '/v1/accounts/' + route)) {
73
+ (response.url && response.url !== accountOrigin + '/v1/accounts/' + route)) {
72
74
  throw new AccountClientError('REDIRECT_REFUSED', 'Account API redirects are forbidden.');
73
75
  }
74
76
  if (!response.ok) {
@@ -116,7 +118,9 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
116
118
  async function currentSession() {
117
119
  const session = await sessionStore.read();
118
120
  if (!session) throw new AccountClientError('NOT_AUTHENTICATED', 'No account session. Sign in first.');
119
- return validateAccountSession(session, now());
121
+ const valid = validateAccountSession(session, now());
122
+ if ((valid.origin || ACCOUNT_ORIGIN) !== accountOrigin) throw new AccountClientError('NOT_AUTHENTICATED', 'Session belongs to another server. Sign in again.');
123
+ return valid;
120
124
  }
121
125
 
122
126
  async function login(credentials = {}) {
@@ -130,7 +134,8 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
130
134
  try { session = validateAccountSession(data, now()); }
131
135
  catch { throw invalidResponse(); }
132
136
  if (data.tokenType !== 'Bearer' || !isAccount(data.account)) throw invalidResponse();
133
- const terms = readTerms(data.account.terms);
137
+ const terms = readTerms(data.account.terms, accountOrigin);
138
+ if (accountOrigin !== ACCOUNT_ORIGIN) session.origin = accountOrigin;
134
139
  try { await sessionStore.write(session); }
135
140
  catch (error) {
136
141
  // Avoid leaving a newly issued session alive when local persistence fails.
@@ -145,7 +150,7 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
145
150
  try {
146
151
  const data = await request('me', 'GET', undefined, session.token);
147
152
  if (!isAccount(data.account)) throw invalidResponse();
148
- const terms = readTerms(data.account.terms);
153
+ const terms = readTerms(data.account.terms, accountOrigin);
149
154
  return { account: data.account, ...(terms && { terms }) };
150
155
  } catch (error) {
151
156
  if (error.code === 'UNAUTHORIZED') await sessionStore.clear();
@@ -160,7 +165,7 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
160
165
  const session = await currentSession();
161
166
  const data = await request('terms', 'POST', { termsVersion: version, accepted: true }, session.token);
162
167
  if (!isAccount(data.account)) throw invalidResponse();
163
- const terms = readTerms(data.account.terms);
168
+ const terms = readTerms(data.account.terms, accountOrigin);
164
169
  if (!terms || !terms.accepted || terms.version !== version) throw invalidResponse();
165
170
  return { terms };
166
171
  }
@@ -173,11 +178,13 @@ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
173
178
  }
174
179
 
175
180
  async function logout() {
181
+ const existing = await sessionStore.read();
182
+ if (existing && (existing.origin || ACCOUNT_ORIGIN) !== accountOrigin) throw new AccountClientError('NOT_AUTHENTICATED', 'Session belongs to another server.');
176
183
  try {
177
184
  const stored = await sessionStore.read();
178
185
  if (!stored) return { revoked: 0 };
179
186
  let session;
180
- try { session = validateAccountSession(stored, now()); }
187
+ try { session = validateAccountSession(stored, now()); if ((session.origin || ACCOUNT_ORIGIN) !== accountOrigin) throw new AccountClientError('NOT_AUTHENTICATED', 'Session belongs to another server.'); }
181
188
  catch (error) { if (error.code === 'SESSION_EXPIRED') return { revoked: 0 }; throw error; }
182
189
  const data = await request('logout', 'POST', {}, session.token);
183
190
  if (!Number.isSafeInteger(data.revoked) || data.revoked < 0) throw invalidResponse();
@@ -15,7 +15,7 @@ class AccountSessionError extends Error {
15
15
  }
16
16
 
17
17
  // The account API uses epoch milliseconds. Never persist credentials or the
18
- // entire login response: the only permitted fields are token and expiresAt.
18
+ // entire login response: only token, expiry and an optional server origin are stored.
19
19
  function validateAccountSession(value, now = Date.now()) {
20
20
  if (!value || typeof value !== 'object' || Array.isArray(value) ||
21
21
  typeof value.token !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(value.token) ||
@@ -25,7 +25,11 @@ function validateAccountSession(value, now = Date.now()) {
25
25
  if (value.expiresAt <= now) {
26
26
  throw new AccountSessionError('SESSION_EXPIRED', 'Account session expired. Sign in again.');
27
27
  }
28
- return { token: value.token, expiresAt: value.expiresAt };
28
+ if (value.origin !== undefined) {
29
+ let url; try { url = new URL(value.origin); } catch { throw new AccountSessionError('INVALID_SESSION', 'Invalid account session origin.'); }
30
+ if (url.origin !== value.origin || !['https:', 'http:'].includes(url.protocol) || url.username || url.password) throw new AccountSessionError('INVALID_SESSION', 'Invalid account session origin.');
31
+ }
32
+ return { token: value.token, expiresAt: value.expiresAt, ...(value.origin && { origin: value.origin }) };
29
33
  }
30
34
 
31
35
  /**
@@ -129,6 +129,13 @@ function mergeFile(srcFile, dstFile, rel, stats) {
129
129
  if (!fs.existsSync(dstFile)) { copyPreservingTime(srcFile, dstFile); stats.added++; return; }
130
130
  const srcJson = readJson(srcFile), dstJson = readJson(dstFile);
131
131
  if (isEntryMap(srcJson) && isEntryMap(dstJson)) {
132
+ // Legacy Maven false values do not prove absence and must never override a
133
+ // confirmed hit, even if their containing cache file is more recent.
134
+ if (rel === "maven-exists-cache.json") {
135
+ const { discardUnverifiedEntries } = require("./maven-presence");
136
+ discardUnverifiedEntries(srcJson);
137
+ discardUnverifiedEntries(dstJson);
138
+ }
132
139
  mergeEntryMaps(srcFile, dstFile, srcJson, dstJson);
133
140
  stats.merged++;
134
141
  return;
@@ -22,7 +22,7 @@ function parse(args) {
22
22
  }
23
23
  return out;
24
24
  }
25
- async function ensureSignedIn({account,store,ask=prompt,interactive=!!(process.stdin.isTTY && process.stderr.isTTY),warn=console.error}) {
25
+ async function ensureSignedIn({account,store,ask=prompt,interactive=!!(process.stdin.isTTY && process.stderr.isTTY),warn=console.error,accountOrigin='https://www.vigievuln.fr'}) {
26
26
  if(store.read()) {
27
27
  try {
28
28
  const result=await account.me(),session=store.read();
@@ -31,7 +31,7 @@ async function ensureSignedIn({account,store,ask=prompt,interactive=!!(process.s
31
31
  catch(error) {if(!['UNAUTHORIZED','NOT_AUTHENTICATED','SESSION_EXPIRED'].includes(error.code))throw error;}
32
32
  }
33
33
  if(!interactive)throw new Error('login required: run vigievuln login in an interactive terminal, then retry');
34
- warn('Sign in to your Vigie Vuln account. Register: https://www.vigievuln.fr/account');
34
+ warn(`Sign in to your Vigie Vuln account at ${accountOrigin}. Register: ${accountOrigin}/account`);
35
35
  const email=await ask('Email: '), password=await ask('Password: ',true);
36
36
  const result=await account.login({email,password});
37
37
  await requireTerms({account,terms:result.terms,ask,interactive,warn});
@@ -44,15 +44,35 @@ async function run(args, dependencies={}) {
44
44
  return (await ensureSignedIn({account,store,...dependencies})).session;
45
45
  }});
46
46
  if(args.some(a=>a==='--help' || a==='-h') || (group==='auth' && !command)) {
47
- console.log(group==='auth' ? 'Usage: vigievuln login | logout | whoami\nAliases: auth login | logout | status (also auth whoami).\nLogin stores an account session only; it does not configure proxy keys.\nMissing/expired sessions require login; an interactive terminal can prompt.'
47
+ console.log(group==='auth' ? 'Usage: vigievuln login | logout | whoami\nAliases: auth login | logout | status (also auth whoami).\nLogin selects the official proxy when no proxy is configured.\nMissing/expired sessions require login; an interactive terminal can prompt.'
48
48
  : 'Usage: vigievuln project status\n vigievuln project push --file <descriptor> (--name <new project> | --id <existing project>)\nUse watch <dir> --help for local collection and safe project updates.');
49
49
  return;
50
50
  }
51
- const store=createAccountSessionStore(),account=createAccountClient({sessionStore:store});
51
+ const store=createAccountSessionStore();
52
+ const config=require('./config');
53
+ const selected=config.get('proxyCache');
54
+ let accountOrigin=require('./account-client').ACCOUNT_ORIGIN;
55
+ if(group==='auth' && selected && !/^(default|vigievuln|https:\/\/api\.vigievuln\.(fr|com)\/?$)$/i.test(selected)) {
56
+ let url; try { url=new URL(selected); } catch { throw new Error('Invalid configured proxy URL.'); }
57
+ if (!['https:','http:'].includes(url.protocol) || url.username || url.password || url.pathname!=='/' || url.search || url.hash) throw new Error('The configured proxy must be an HTTP(S) origin without credentials or a path.');
58
+ if (url.protocol==='http:' && !['localhost','127.0.0.1','[::1]'].includes(url.hostname)) throw new Error('Login to a remote proxy requires HTTPS.');
59
+ accountOrigin=url.origin;
60
+ }
61
+ const account=createAccountClient({sessionStore:store,accountOrigin});
52
62
  if(group==='auth') {
53
63
  if(rest.length)throw new Error('unexpected authentication option');
54
64
  if(['login','status','whoami'].includes(command)) {
55
- const result=await ensureSignedIn({account,store,...dependencies});console.log(`Signed in as ${result.account.email}.`);return;
65
+ const result=await ensureSignedIn({account,store,accountOrigin,...dependencies});
66
+ if(command==='login' && !selected) {config.set('proxyCache','vigievuln');console.log('Official VigieVuln proxy configured for future scans.');}
67
+ if(command==='login' && accountOrigin===require('./account-client').ACCOUNT_ORIGIN && config.get('proxyCacheTokenOrigin')) {
68
+ config.set('proxyCacheToken',null);config.set('proxyCacheTokenOrigin',null);
69
+ }
70
+ if(command==='login' && accountOrigin!==require('./account-client').ACCOUNT_ORIGIN &&
71
+ (config.get('proxyCacheTokenOrigin')!==accountOrigin || !config.get('proxyCacheToken'))) {
72
+ const key=await account.createProxyKey();config.set('proxyCacheToken',key.token);config.set('proxyCacheTokenOrigin',accountOrigin);
73
+ console.log(`Proxy key saved for ${accountOrigin}.`);
74
+ }
75
+ console.log(`Signed in as ${result.account.email}.`);return;
56
76
  }
57
77
  if(command==='logout') {await account.logout();console.log('Signed out.');return;}
58
78
  throw new Error('usage: vigievuln auth login|status|logout');
@@ -22,14 +22,14 @@ const cveIndexScanner = {
22
22
  if (opts.hostedProxy && !opts.offline && !opts.cveOffline) {
23
23
  const keys = new Set();
24
24
  for (const dep of deps.values()) {
25
- if (dep.ecosystem === "npm" || dep.provenance === "binary") continue;
25
+ if ((dep.ecosystem && dep.ecosystem !== "maven") || dep.provenance === "binary") continue;
26
26
  const group = String(dep.groupId || "").toLowerCase(), artifact = String(dep.artifactId || "").toLowerCase();
27
27
  if (group && artifact) keys.add("p:" + group + ":" + artifact);
28
28
  if (artifact) keys.add("a:" + artifact);
29
29
  }
30
30
  const idx = newIndex(), all = [...keys], seen = new Set();
31
31
  for (let i = 0; i < all.length; i += 200) {
32
- const res = await require("../providers").getResource("github", "cve-maven", { keys: all.slice(i, i + 200) }, { noStore: true, streaming: true });
32
+ const res = await require("../providers").getResource("github", "cve-maven", { keys: all.slice(i, i + 200) });
33
33
  if (!res.ok) throw new Error(`hosted CVE index unavailable (HTTP ${res.status})`);
34
34
  const data = await res.json();
35
35
  if (!Array.isArray(data.cves)) throw new Error("invalid hosted CVE index response");
@@ -117,8 +117,9 @@ async function fetchPackument(name, opts = {}) {
117
117
  const ah = authHeaderFor(base);
118
118
  if (ah) headers.Authorization = ah;
119
119
  try {
120
+ const hosted = base.name === "public" && require("../../providers").hasHostedProxy();
120
121
  const res = await require("../../providers").getResource("npm", "package", { name },
121
- { fetcher, headers, signal: AbortSignal.timeout(timeoutMs),
122
+ { fetcher, headers, ...(hosted ? { requestTimeoutMs: timeoutMs } : { signal: AbortSignal.timeout(timeoutMs) }),
122
123
  ...(base.name === "public" ? {} : { urlOverride: url, direct: true }) });
123
124
  if (res.ok) return await res.json();
124
125
  lastErr = `HTTP ${res.status}`;
package/lib/cve-match.js CHANGED
@@ -438,10 +438,9 @@ function matchDepsAgainstCves(resolvedDeps, cveIndex, opts = {}) {
438
438
 
439
439
  const all = [];
440
440
  for (const dep of resolvedDeps.values()) {
441
- // The CVEProject Maven index has no npm coverage — skip npm deps here.
442
- // They are caught by the OSV pipeline (which is multi-ecosystem) and
443
- // the CPE refinement step (post-NVD).
444
- if (dep.ecosystem === "npm") continue;
441
+ // The CVEProject index contains Maven coordinates only. Other ecosystems
442
+ // are handled by their own advisory sources and must not match by artifact.
443
+ if (dep.ecosystem && dep.ecosystem !== "maven") continue;
445
444
  if (dep.provenance === "binary") continue; // no resolved coordinate yet (Plan 2 identifies it)
446
445
  const key = `${dep.groupId}:${dep.artifactId}`.toLowerCase();
447
446
  // Tier 1: exact packageName match
package/lib/cve-report.js CHANGED
@@ -897,7 +897,7 @@ function renderDetailPanel(m) {
897
897
  if (cve.aliases?.length) {
898
898
  const aliasItems = cve.aliases.map(a => {
899
899
  if (a.startsWith("GHSA-")) return `<li><a href="https://github.com/advisories/${esc(a)}" target="_blank">${esc(a)}</a> (GitHub)</li>`;
900
- if (a.startsWith("CVE-")) return `<li><a href="https://nvd.nist.gov/vuln/detail/${esc(a)}" target="_blank">${esc(a)}</a> (NVD)</li>`;
900
+ if (/^CVE-\d{4}-\d{4,}$/i.test(a)) return `<li><a href="https://www.vigievuln.fr/cve/${encodeURIComponent(a.toUpperCase())}" target="_blank" rel="noopener noreferrer">${esc(a)}</a></li>`;
901
901
  return `<li>${esc(a)}</li>`;
902
902
  }).join("");
903
903
  sections.push(section(t("Aliases"), `<ul class="ref-list">${aliasItems}</ul>`, { open: false }));
@@ -966,7 +966,7 @@ function formatCwesVerbose(cwes) {
966
966
  function renderCveRow(m, opts = {}) {
967
967
  const { withAction } = opts;
968
968
  const advisoryId = String(m.cve.id || "");
969
- const link = /^CVE-\d{4}-\d{4,}$/i.test(advisoryId) ? `https://nvd.nist.gov/vuln/detail/${encodeURIComponent(advisoryId)}` :
969
+ const link = /^CVE-\d{4}-\d{4,}$/i.test(advisoryId) ? `https://www.vigievuln.fr/cve/${encodeURIComponent(advisoryId.toUpperCase())}` :
970
970
  /^GHSA-[A-Za-z0-9-]+$/i.test(advisoryId) ? `https://github.com/advisories/${encodeURIComponent(advisoryId)}` : null;
971
971
  const advisoryCell = link ? `<a href="${link}" target="_blank" rel="noopener">${esc(advisoryId)}</a>` : esc(advisoryId);
972
972
  const sourceParts = m.source ? String(m.source).split("+") : [];
@@ -1980,8 +1980,8 @@ 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 candidate = m.cve.id?.startsWith("CVE-")
1984
- ? `https://nvd.nist.gov/vuln/detail/${esc(m.cve.id)}`
1983
+ const candidate = /^CVE-\d{4}-\d{4,}$/i.test(String(m.cve.id || ""))
1984
+ ? `https://www.vigievuln.fr/cve/${encodeURIComponent(String(m.cve.id).toUpperCase())}`
1985
1985
  : (m.cve.osvRefs?.[0]?.url || null);
1986
1986
  let href = null;
1987
1987
  try { if (candidate && ['https:', 'http:'].includes(new URL(candidate).protocol)) href = candidate; } catch { /* untrusted advisory URL */ }
@@ -38,11 +38,16 @@ async function createProxyKey(account) {
38
38
  async function checkHostedProxy(url, token, fetcher = globalThis.fetch) {
39
39
  let response;
40
40
  try {
41
- response = await fetcher(url + "/v1/proxy/status", { headers: { authorization: "Bearer " + token },
41
+ response = await fetcher(url + "/v1/proxy/status", { headers: { authorization: "Bearer " + token, "x-vigievuln-client-version": require('../package.json').version },
42
42
  redirect: "error", signal: AbortSignal.timeout(15000) });
43
43
  } catch { throw new Error("VigieVuln proxy is unreachable; check your connection and proxy endpoint"); }
44
44
  try {
45
45
  if (response.status === 401 || response.status === 403) throw new Error("VigieVuln proxy key is invalid, expired or revoked; create a key from your verified account");
46
+ if (response.status === 426) {
47
+ let data; try { data = await response.json(); } catch { /* keep the generic upgrade message */ }
48
+ const minimum = typeof data?.minimumCliVersion === 'string' && /^\d+\.\d+\.\d+$/.test(data.minimumCliVersion) ? ` ${data.minimumCliVersion} or newer` : '';
49
+ throw new Error(`VigieVuln${minimum} is required by the proxy. Update with npm install -g vigievuln@latest or visit https://github.com/9pings/VigieVuln/releases`);
50
+ }
46
51
  if (!response.ok) throw new Error(`VigieVuln proxy is unavailable (HTTP ${response.status})`);
47
52
  const data = await response.json();
48
53
  if (data.ok !== true || data.service !== "vigievuln-proxy") throw new Error("unexpected VigieVuln proxy response");
package/lib/maven-repo.js CHANGED
@@ -128,7 +128,7 @@ function buildRepoList(userRepos, extraRepos = [], { mirrors = true } = {}) {
128
128
  for (const r of userRepos || []) push(r);
129
129
  for (const r of extraRepos || []) push(r);
130
130
  push(MAVEN_CENTRAL);
131
- if (mirrors) for (const m of DEFAULT_CENTRAL_MIRRORS) push(m);
131
+ if (mirrors && !require('./providers').hasHostedProxy()) for (const m of DEFAULT_CENTRAL_MIRRORS) push(m);
132
132
  return out;
133
133
  }
134
134
 
@@ -189,10 +189,12 @@ async function tryRepos(repos, pathSuffix, opts = {}) {
189
189
  if (ah) headers.Authorization = ah;
190
190
  let r;
191
191
  try {
192
- r = await withDeadline(timeoutMs, signal => require("./providers").getResource("maven", "artifact",
193
- { path: pathSuffix.replace(/^\/+/, ""), method },
194
- { fetcher, headers, signal, ...(url === `https://repo1.maven.org/maven2/${pathSuffix.replace(/^\/+/, "")}`
195
- ? {} : { urlOverride: url, direct: true }) }));
192
+ const providers = require("./providers");
193
+ const official = repo.url === MAVEN_CENTRAL.url && !repo.auth && !repo.token;
194
+ const params = { path: pathSuffix.replace(/^\/+/, ""), method };
195
+ if (official && providers.hasHostedProxy()) r = await providers.getResource("maven", "artifact", params, {fetcher, headers, requestTimeoutMs:timeoutMs});
196
+ else r = await withDeadline(timeoutMs, signal => providers.getResource("maven", "artifact", params,
197
+ { fetcher, headers, signal, ...(official ? {} : { urlOverride: url, direct: true }) }));
196
198
  } catch (err) {
197
199
  // Unreachable or timed out: a mirror that does this once will do it for every
198
200
  // remaining coordinate, so take it out of the rotation for the run.
@@ -234,7 +236,10 @@ async function reachableRepos(repos, opts = {}) {
234
236
  const ah = repoAuthHeader(repo);
235
237
  if (ah) headers.Authorization = ah;
236
238
  try {
237
- await withDeadline(timeoutMs, signal => require("./providers").getResource("maven", "preflight", {},
239
+ const providers = require("./providers");
240
+ if (providers.hasHostedProxy() && repo.url === MAVEN_CENTRAL.url && !repo.auth && !repo.token)
241
+ await providers.getResource("maven", "preflight", {}, {fetcher, headers, requestTimeoutMs:timeoutMs});
242
+ else await withDeadline(timeoutMs, signal => providers.getResource("maven", "preflight", {},
238
243
  { fetcher, headers, signal, urlOverride: repo.url, direct: true }));
239
244
  return repo;
240
245
  } catch {
package/lib/nvd.js CHANGED
@@ -183,8 +183,9 @@ const MIRROR_CONCURRENCY = 16;
183
183
  async function fetchFromMirror(cveId, opts = {}) {
184
184
  const { fetcher = globalThis.fetch } = opts;
185
185
  try {
186
- const m = await require("./providers").getResource("nvd", "cve-mirror", { id: cveId },
187
- { fetcher, headers: { "User-Agent": "vigievuln-nvd-enrich" }, signal: AbortSignal.timeout(MIRROR_TIMEOUT_MS) });
186
+ const providers = require("./providers");
187
+ const m = await providers.getResource("nvd", "cve-mirror", { id: cveId },
188
+ { fetcher, headers: { "User-Agent": "vigievuln-nvd-enrich" }, ...(providers.hasHostedProxy() ? {requestTimeoutMs:MIRROR_TIMEOUT_MS, retryProxyDenied:false, noSourceRetry:true} : {signal:AbortSignal.timeout(MIRROR_TIMEOUT_MS)}) });
188
189
  if (m.status === 404) return { absent: true };
189
190
  if (!m.ok) return { failed: true };
190
191
  const raw = await m.json();
@@ -223,11 +224,11 @@ async function fetchOne(cveId, opts = {}) {
223
224
  const url = `${NVD_BASE}?cveId=${encodeURIComponent(cveId)}`;
224
225
  const providers = require("./providers");
225
226
  const health = require("./source-health");
226
- const deadline = () => (mirror ? { signal: AbortSignal.timeout(MIRROR_TIMEOUT_MS) } : {});
227
+ const deadline = () => providers.hasHostedProxy() ? {requestTimeoutMs:MIRROR_TIMEOUT_MS} : (mirror ? { signal: AbortSignal.timeout(MIRROR_TIMEOUT_MS) } : {});
227
228
 
228
229
  let nvdReason;
229
230
  try {
230
- const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, ...deadline() });
231
+ const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, ...deadline(), ...(providers.hasHostedProxy() && mirror ? {retryProxyDenied:false,noSourceRetry:true} : {}) });
231
232
  if (r.status === 404) { writeCache(cveId, null); return null; }
232
233
  if (r.ok) {
233
234
  const data = await r.json();
@@ -270,7 +271,8 @@ async function enrichMatches(matches, opts = {}) {
270
271
  for (const m of matches) if (m.cve?.id?.startsWith("CVE-")) uniqueCves.add(m.cve.id);
271
272
  // `opts.hasKey` lets a test pin the key/no-key branch whatever ~/.fad-checker holds.
272
273
  const hasKey = opts.hasKey ?? !!getNvdApiKey();
273
- const burst = getBurstSize();
274
+ const hosted = !offline && require("./providers").hasHostedProxy();
275
+ const burst = hosted ? 10 : getBurstSize();
274
276
 
275
277
  // Partition cached vs live up-front so the progress display reflects the
276
278
  // actual work to do (the user's "stuck at OSV" complaint was caused by
@@ -319,10 +321,10 @@ async function enrichMatches(matches, opts = {}) {
319
321
 
320
322
  if (liveIds.length && !onProgress) {
321
323
  const etaSec = Math.ceil((liveIds.length / burst) * (NVD_WINDOW_MS / 1000));
322
- const keyHint = hasKey ? "with API key (50/30s)" : "no API key — throttled to 5/30s, run `vigievuln --set-nvd-key <KEY>` (free, instant) to be 10× faster";
324
+ const keyHint = hosted ? "via hosted proxy" : hasKey ? "with API key (50/30s)" : "no API key — throttled to 5/30s, run `vigievuln --set-nvd-key <KEY>` (free, instant) to be 10× faster";
323
325
  const cachedCount = byId.size;
324
326
  const cachedHint = cachedCount ? `, ${cachedCount} cached` : "";
325
- console.log(`🔍 NVD: enriching ${liveIds.length} CVEs${cachedHint} — ${keyHint}. ETA ~${etaSec}s.`);
327
+ console.log(`🔍 NVD: enriching ${liveIds.length} CVEs${cachedHint} — ${keyHint}.${hosted ? '' : ` ETA ~${etaSec}s.`}`);
326
328
  } else if (uniqueCves.size && !onProgress) {
327
329
  console.log(`🔍 NVD: ${uniqueCves.size} CVEs (all cached).`);
328
330
  }
@@ -352,7 +354,7 @@ async function enrichMatches(matches, opts = {}) {
352
354
  printProgress();
353
355
 
354
356
  // Respect the rolling 30s window before starting the next burst.
355
- if (i + burst < liveIds.length) {
357
+ if (!hosted && i + burst < liveIds.length) {
356
358
  const since = Date.now() - windowStart;
357
359
  if (since < NVD_WINDOW_MS) await sleep(NVD_WINDOW_MS - since);
358
360
  }
package/lib/osv.js CHANGED
@@ -315,7 +315,9 @@ async function queryBatch(deps, opts = {}) {
315
315
  const pkgName = osvPkgName(d);
316
316
  queries.push({
317
317
  package: { name: pkgName, ecosystem },
318
- version: d.version,
318
+ // Maven property expansion can retain surrounding XML whitespace. OSV
319
+ // expects the actual version, and one invalid item rejects the whole batch.
320
+ version: String(d.version).trim(),
319
321
  });
320
322
  }
321
323
  }
@@ -16,8 +16,9 @@ const providers = [
16
16
  require("./euvd"), require("./certfr"),
17
17
  ];
18
18
  const byId = new Map(providers.map(provider => [provider.id, provider]));
19
- let route = { hosted: false, proxyUrl: null, token: null, store: null, health: null, fetcher: null, maxBodyBytes: 32 * 1024 * 1024 };
19
+ let route = { hosted: false, proxyUrl: null, token: null, store: null, hostedStore: null, health: null, fetcher: null, maxBodyBytes: 32 * 1024 * 1024 };
20
20
  const inFlight = new Map();
21
+ const proxyThrottle = require('../proxy-throttle').createProxyThrottle();
21
22
  const copyResponse = response => typeof response?.clone === "function" ? response.clone() : response;
22
23
 
23
24
  function configureResourceRoute(options = {}) {
@@ -62,9 +63,9 @@ async function getResource(id, type, params, options = {}) {
62
63
  const headers = new Headers(outboundHeaders);
63
64
  const target = options.urlOverride || request.url;
64
65
  const key = providerKey(id, type, params, headers) + (options.urlOverride ? `:origin:${crypto.createHash("sha256").update(target).digest("hex")}` : "");
65
- // Hosted online requests must reach the proxy's one-hour freshness policy even
66
- // when a caller supplied a local store explicitly. Offline mode may use it.
67
- const store = options.urlOverride || options.streaming || (hasHostedProxy() && !options.offline) ? null : (options.store || route.store);
66
+ // Only the dedicated, origin-scoped hosted store contains proxy-confirmed data.
67
+ // Never mistake an older direct-source cache for a fresh hosted response.
68
+ const store = options.urlOverride || options.streaming ? null : (hasHostedProxy() && !options.offline ? route.hostedStore : (options.store || route.store));
68
69
  let entry = store?.get(key) || null;
69
70
  if (entry && id === "github" && type === "publisher-advisories" && !entry.responseHeaders) entry = null;
70
71
  if (entry && Date.now() - entry.fetchedAt < entry.ttlMs) return cachedResponse(entry);
@@ -83,12 +84,14 @@ async function getResource(id, type, params, options = {}) {
83
84
  let response;
84
85
  if (route.proxyUrl && !options.direct && !options.urlOverride) {
85
86
  const proxyHeaders = { "content-type": "application/json" };
87
+ if (route.hosted) proxyHeaders["x-vigievuln-client-version"] = require('../../package.json').version;
86
88
  if (route.token) proxyHeaders["x-fad-proxy-token"] = route.token;
87
- const callProxy = () => fetcher(`${route.proxyUrl}/v1/resource`, { method: "POST", headers: proxyHeaders,
89
+ const sendProxy = () => fetcher(`${route.proxyUrl}/v1/resource`, { method: "POST", headers: proxyHeaders,
88
90
  redirect: "error", // Never forward a proxy credential to a redirected origin.
89
91
  body: JSON.stringify({ provider: id, type, params, headers: Object.fromEntries(headers.entries()) }),
90
- ...(options.signal ? { signal: options.signal } : {}) });
91
- response = route.health && !entry
92
+ ...((options.signal || route.hosted) ? { signal: options.signal || AbortSignal.timeout(options.requestTimeoutMs || 15000) } : {}) });
93
+ const callProxy = () => route.hosted ? proxyThrottle.request(sendProxy, options.signal, {retryDenied: options.retryProxyDenied !== false, retryTransient: !options.noSourceRetry}) : sendProxy();
94
+ response = route.health && !entry && !route.hosted && !options.noSourceRetry
92
95
  ? await require("../source-health").guardedFetch({ health: route.health,
93
96
  fetch: callProxy, ...(route.sleep ? { sleep: route.sleep } : {}) })(request.url,
94
97
  options.signal ? { signal: options.signal } : undefined)
@@ -98,19 +101,25 @@ async function getResource(id, type, params, options = {}) {
98
101
  ...(options.signal ? { signal: options.signal } : {}) });
99
102
  }
100
103
  if (response.headers?.get?.("x-fad-proxy") === "stale") route.health?.markStale?.(id, response.headers.get("x-fad-proxy-fetched-at"));
104
+ if (hasHostedProxy() && route.health && !options.noSourceRetry && (response.status === 403 || response.status === 429 || response.status >= 500)) {
105
+ const source = require('../source-health').sourceForUrl(request.url);
106
+ if (source) route.health.markOutage(source.id, {url: request.url, code: `HTTP ${response.status}`});
107
+ }
101
108
  if (entry && (response.status === 403 || response.status === 429 || response.status >= 500)) {
102
109
  route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString());
103
110
  return cachedResponse(entry, "stale");
104
111
  }
105
112
  if (!response.ok || !store || options.noStore) return response;
113
+ // A mirror or batch without an upstream timestamp cannot establish freshness.
114
+ if (hasHostedProxy() && (response.headers.get("x-fad-proxy") === "stale" || !Number.isFinite(Date.parse(response.headers.get("x-fad-proxy-fetched-at") || "")))) return response;
106
115
  const length = Number(response.headers.get("content-length"));
107
116
  if (Number.isFinite(length) && length > route.maxBodyBytes) return response;
108
117
  const body = Buffer.from(await response.clone().arrayBuffer());
109
- try { persist(store, key, response, body, provider.ttlMs); } catch { /* source result remains usable */ }
118
+ try { persist(store, key, response, body, hasHostedProxy() ? Math.min(provider.ttlMs || 3600000, 3600000) : provider.ttlMs); } catch { /* source result remains usable */ }
110
119
  return response;
111
120
  } catch (error) {
112
121
  if (entry) { route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString()); return cachedResponse(entry, "stale"); }
113
- if (route.health && !options.urlOverride && !route.health.isDown(require("../source-health").sourceForUrl(request.url)?.id)) {
122
+ if (route.health && !options.noSourceRetry && !options.urlOverride && !route.health.isDown(require("../source-health").sourceForUrl(request.url)?.id)) {
114
123
  const { sourceForUrl } = require("../source-health");
115
124
  const source = sourceForUrl(request.url);
116
125
  if (source) route.health.markOutage(source.id, { url: request.url, code: error.code || error.message });
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // The hosted service permits 7200 requests/minute per key. Leave headroom for
4
+ // concurrent scans and preflight, and coordinate all providers in this process.
5
+ function createProxyThrottle({ intervalMs = 10, maxPerMinute = 6000, sleep = (ms, signal) => require('node:timers/promises').setTimeout(ms, undefined, {signal}), now = Date.now, warn = console.error } = {}) {
6
+ let next = 0, blockedUntil = 0, warnedPacing = false, requests = 0, window = -1, count = 0;
7
+ const lastWarning = new Map();
8
+ function reserve(earliest) {
9
+ let slot = Math.max(now(), next, blockedUntil, earliest);
10
+ let current = Math.floor(slot / 60000);
11
+ if (current !== window) { window = current; count = 0; }
12
+ if (count >= maxPerMinute) {
13
+ slot = (window + 1) * 60000; window++; count = 0;
14
+ warn(`Proxy: request budget reached; waiting ${Math.ceil(Math.max(0, slot - now()) / 1000)}s for the next window.`);
15
+ }
16
+ count++;
17
+ next = slot + intervalMs;
18
+ return slot;
19
+ }
20
+ function abortError() { const error = new Error('Proxy request aborted while waiting for rate limit.'); error.name = 'AbortError'; return error; }
21
+ async function wait(ms, signal) {
22
+ if (signal?.aborted) throw abortError();
23
+ if (!signal) return sleep(ms);
24
+ let onAbort;
25
+ try { await Promise.race([sleep(ms, signal), new Promise((_, reject) => { onAbort = () => reject(abortError()); signal.addEventListener('abort', onAbort, {once:true}); })]); }
26
+ finally { signal.removeEventListener('abort', onAbort); }
27
+ }
28
+ async function acquire(signal) {
29
+ let slot = reserve(0);
30
+ if (++requests === 10 && !warnedPacing) { warnedPacing = true; warn('Proxy: pacing requests to respect the server rate limit.'); }
31
+ for (;;) {
32
+ if (slot < blockedUntil) slot = reserve(blockedUntil);
33
+ const delay = slot - now();
34
+ if (delay <= 0) break;
35
+ await wait(delay, signal);
36
+ }
37
+ }
38
+ function delayFrom(response) {
39
+ const raw = response.headers?.get?.('retry-after');
40
+ const seconds = raw && /^\d+$/.test(raw) ? Number(raw) : null;
41
+ const date = raw && seconds === null ? Date.parse(raw) : NaN;
42
+ return Math.max(1000, seconds !== null ? seconds * 1000 : Number.isFinite(date) ? date - now() : 10000);
43
+ }
44
+ async function request(fetcher, signal, {retryDenied = true, retryTransient = true} = {}) {
45
+ let limitRetries = 0, transientRetries = 0;
46
+ for (;;) {
47
+ await acquire(signal);
48
+ const response = await fetcher();
49
+ const limited = response.status === 429 || (retryDenied && response.status === 503 && response.headers?.get?.('x-fad-proxy') === 'denied');
50
+ if (!limited) {
51
+ if (!retryTransient || ![502,503,504].includes(response.status) || transientRetries++ >= 2 || (response.status === 503 && !retryDenied && response.headers?.get?.('x-fad-proxy') === 'denied')) return response;
52
+ if (response.body && !response.body.locked) void response.body.cancel().catch(() => {});
53
+ await wait(transientRetries * 500, signal);
54
+ continue;
55
+ }
56
+ if (limitRetries >= 3) return response;
57
+ limitRetries++;
58
+ const delay = delayFrom(response);
59
+ if (delay > 60000) { warn(`Proxy rate limit: retry requested after ${Math.ceil(delay / 1000)}s; stopping this request.`); return response; }
60
+ blockedUntil = Math.max(blockedUntil, now() + delay);
61
+ next = Math.max(next, blockedUntil);
62
+ if (!lastWarning.has(response.status) || now() - lastWarning.get(response.status) >= 10000) {
63
+ lastWarning.set(response.status, now());
64
+ warn(`Proxy rate limit (HTTP ${response.status}): waiting ${Math.ceil(delay / 1000)}s before retrying (attempt ${limitRetries}/3).`);
65
+ }
66
+ if (response.body && !response.body.locked) void response.body.cancel().catch(() => {});
67
+ }
68
+ }
69
+ return { request };
70
+ }
71
+ module.exports = { createProxyThrottle };
@@ -54,6 +54,7 @@ const TTL_BY_SOURCE = {
54
54
  };
55
55
 
56
56
  const DEFAULT_MAX_BODY_BYTES = 32 * 1024 * 1024;
57
+ const NPM_PROJECTION_MAX_BYTES = 64 * 1024 * 1024;
57
58
  const DEFAULT_MAX_TRANSFER_BYTES = 1024 * 1024 * 1024;
58
59
  const DEFAULT_MAX_STORE_BYTES = 2 * 1024 * 1024 * 1024;
59
60
  const DEFAULT_UPSTREAM_TIMEOUT_MS = 120000;
@@ -358,7 +359,8 @@ function createResourceEngine(opts = {}) {
358
359
  try {
359
360
  // JSON must be fully validated even when too large for a store row. Bound
360
361
  // that read independently of the (potentially 1 GB) archive transfer cap.
361
- const transferLimit = json ? Math.min(maxTransferBytes, Math.max(DEFAULT_MAX_BODY_BYTES, maxBodyBytes)) : maxTransferBytes;
362
+ const largeNpm = resource?.provider === 'npm' && resource.type === 'package' && typeof transform === 'function';
363
+ const transferLimit = json ? Math.min(maxTransferBytes, Math.max(DEFAULT_MAX_BODY_BYTES, maxBodyBytes, largeNpm ? NPM_PROJECTION_MAX_BYTES : 0)) : maxTransferBytes;
362
364
  if (Number(up.headers.get("content-length")) > transferLimit) {
363
365
  await up.body.cancel(); throw new Error("proxy transfer limit exceeded");
364
366
  }
@@ -368,13 +370,15 @@ function createResourceEngine(opts = {}) {
368
370
  const replaced = json || (bytes <= cacheLimitBytes && transform && resource) ? await transformSlots(async () => {
369
371
  if (signal.aborted) throw signal.reason;
370
372
  const buffer = await writer.read();
371
- if (json) validateResourceJson(resource, parseUpstreamJson(buffer));
372
- const result = bytes <= cacheLimitBytes && transform && resource ? await transform(resource, buffer) : null;
373
+ const parsed = json ? parseUpstreamJson(buffer) : undefined;
374
+ if (json) validateResourceJson(resource, parsed);
375
+ const result = (bytes <= cacheLimitBytes || largeNpm) && transform && resource ? await transform(resource, buffer, parsed) : null;
373
376
  if (json && result) validateResourceJson(resource, parseUpstreamJson(result));
377
+ if (largeNpm && bytes > cacheLimitBytes && (!result || result.length > cacheLimitBytes)) throw new Error('oversized npm metadata could not be projected safely');
374
378
  if (signal.aborted) throw signal.reason;
375
379
  return result;
376
380
  }) : null;
377
- if (bytes <= cacheLimitBytes) {
381
+ if (bytes <= cacheLimitBytes || (largeNpm && replaced && replaced.length <= cacheLimitBytes)) {
378
382
  if (replaced) {
379
383
  await writer.abort();
380
384
  const kept = { ...metadata, bytes: replaced.length };
@@ -501,6 +505,9 @@ function createResourceEngine(opts = {}) {
501
505
  const waits = [];
502
506
  const reserved = [];
503
507
  let awaitedBytes = 0, oldestStale = null;
508
+ // A batched response is only as fresh as its oldest member. Missing items
509
+ // are fetched during this request, so its start is a conservative timestamp.
510
+ const oldestFetchedAt = entries.reduce((oldest, entry) => entry ? Math.min(oldest, entry.fetchedAt) : oldest, Date.now());
504
511
  const markStale = entry => { oldestStale = Math.min(oldestStale ?? entry.fetchedAt, entry.fetchedAt); };
505
512
  const assignResult = (i, body) => {
506
513
  awaitedBytes += Buffer.byteLength(JSON.stringify(body));
@@ -575,7 +582,7 @@ function createResourceEngine(opts = {}) {
575
582
  return sendJson(res, 502, { error: error.message }, { "x-fad-proxy": "error" });
576
583
  }
577
584
  return sendJson(res, 200, batch.merge(results), { "x-fad-proxy": oldestStale != null ? "stale" : reserved.length ? "miss" : "hit",
578
- ...(oldestStale != null ? { "x-fad-proxy-fetched-at": new Date(oldestStale).toISOString() } : {}) });
585
+ "x-fad-proxy-fetched-at": new Date(oldestStale ?? oldestFetchedAt).toISOString() });
579
586
  }
580
587
 
581
588
  const wordfenceProjection = require("./wordfence").createWordfenceProjection({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vigievuln",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
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",
package/vigievuln.js CHANGED
@@ -69,6 +69,7 @@ if (process.argv.includes("--completion")) {
69
69
  // -------- --set-nvd-key shortcut (must run before required-options parse) --------
70
70
  if (process.argv.includes("--set-proxy-cache-token") || process.argv.includes("--unset-proxy-cache-token")) {
71
71
  const config = require("./lib/config");
72
+ config.set("proxyCacheTokenOrigin", null);
72
73
  if (process.argv.includes("--unset-proxy-cache-token")) config.set("proxyCacheToken", null);
73
74
  else {
74
75
  const token = process.argv[process.argv.indexOf("--set-proxy-cache-token") + 1];
@@ -613,12 +614,22 @@ if (!options.offline && !options.proxyCacheToken && !process.env.VIGIEVULN_PROXY
613
614
  }
614
615
  try { Object.assign(options, require("./lib/hosted-proxy").resolveHostedProxy({ ...options, allowProxyLogin: !!hostedAccountSession || !!(process.stdin.isTTY && process.stderr.isTTY) })); }
615
616
  catch (err) { console.error(chalk.red(`❌ ${err.message}`)); process.exit(2); }
617
+ const savedProxyTokenOrigin = require('./lib/config').get('proxyCacheTokenOrigin');
618
+ if (options.proxyCache && options.proxyCacheToken && savedProxyTokenOrigin &&
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
+ savedProxyTokenOrigin !== String(options.proxyCache).replace(/\/+$/, '')) {
623
+ console.error(chalk.red('❌ The saved proxy key belongs to another server. Sign in to the configured proxy or provide its key explicitly.'));
624
+ process.exit(2);
625
+ }
616
626
  // A saved official account key must never follow a changed proxy URL to an
617
627
  // unrelated service. Custom proxies require a token supplied for this run.
618
628
  if (options.proxyCache && !options.vigievulnProxy && options.proxyCacheToken &&
619
629
  !program.getOptionValueSource('proxyCacheToken')?.match(/^(cli|env)$/) &&
620
630
  !Object.hasOwn(_layers.fileLayer, 'proxyCacheToken') && !Object.hasOwn(_layers.envLayer, 'proxyCacheToken') &&
621
- !process.env.VIGIEVULN_PROXY_CACHE_TOKEN && !process.env.FAD_PROXY_CACHE_TOKEN) {
631
+ !process.env.VIGIEVULN_PROXY_CACHE_TOKEN && !process.env.FAD_PROXY_CACHE_TOKEN &&
632
+ require('./lib/config').get('proxyCacheTokenOrigin') !== String(options.proxyCache).replace(/\/+$/, '')) {
622
633
  console.error(chalk.red('❌ A saved proxy key cannot be sent to a custom proxy. Supply its token explicitly for this run.'));
623
634
  process.exit(2);
624
635
  }
@@ -666,7 +677,8 @@ if (!options.offline) {
666
677
  configureResourceRoute({ proxyUrl: options.proxyCache, hosted: !!options.vigievulnProxy,
667
678
  token: options.proxyCacheToken || (process.env.VIGIEVULN_PROXY_CACHE_TOKEN ?? process.env.FAD_PROXY_CACHE_TOKEN) || null,
668
679
  health: sourceHealth, fetcher: baseFetch,
669
- store: options.vigievulnProxy ? null : createCacheStore(require("node:path").join(require("./lib/cache-directory").getCacheDir(), "resource-cache")) });
680
+ store: options.vigievulnProxy ? null : createCacheStore(require("node:path").join(require("./lib/cache-directory").getCacheDir(), "resource-cache")),
681
+ hostedStore: options.vigievulnProxy ? createCacheStore(require("node:path").join(require("./lib/cache-directory").getCacheDir(), "hosted-resources", require("node:crypto").createHash("sha256").update(options.proxyCache).digest("hex"))) : null });
670
682
  } catch (err) {
671
683
  console.error(chalk.red(`❌ ${err.message}`));
672
684
  process.exit(2);
@@ -868,6 +880,7 @@ async function timedPhase(label, fn) {
868
880
  await require("./lib/account-terms").requireTerms({account, terms:current.terms, ask});
869
881
  options.proxyCacheToken = await require("./lib/hosted-proxy").createProxyKey(account);
870
882
  require("./lib/config").set("proxyCacheToken", options.proxyCacheToken);
883
+ require("./lib/config").set("proxyCacheTokenOrigin", null);
871
884
  require("./lib/providers").configureResourceRoute({proxyUrl:options.proxyCache,token:options.proxyCacheToken});
872
885
  console.error("Proxy key created from your signed-in account and saved for future scans.");
873
886
  } else {
@@ -877,6 +890,7 @@ async function timedPhase(label, fn) {
877
890
  const password = await ask("Password: ", true);
878
891
  options.proxyCacheToken = await require("./lib/hosted-proxy").loginForProxy({email,password,ask});
879
892
  require("./lib/config").set("proxyCacheToken", options.proxyCacheToken);
893
+ require("./lib/config").set("proxyCacheTokenOrigin", null);
880
894
  require("./lib/providers").configureResourceRoute({proxyUrl:options.proxyCache,token:options.proxyCacheToken});
881
895
  console.error("Proxy key saved for future scans.");
882
896
  }
@@ -934,6 +948,11 @@ async function timedPhase(label, fn) {
934
948
  if (excludePath.length) ui.kv("exclude-path", chalk.white(excludePath.join(chalk.dim(", "))));
935
949
  if (!defaultExcludes) ui.kv("default-excludes", chalk.yellow("off (walking node_modules/vendor/.git/…)"));
936
950
  ui.kv("mode", chalk.white(runMode));
951
+ if (options.proxyCache && !options.offline) {
952
+ let proxyDisplay = 'configured';
953
+ try { const url = new URL(options.proxyCache); url.username = ''; url.password = ''; url.search = ''; url.hash = ''; proxyDisplay = url.toString(); } catch { /* do not print malformed credentials */ }
954
+ ui.kv("proxy", chalk.white(proxyDisplay));
955
+ }
937
956
 
938
957
  let wrotePom = 0;
939
958
 
@@ -1430,7 +1449,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1430
1449
  else ui.info(chalk.dim("First scans may take longer while caches fill."));
1431
1450
 
1432
1451
  const hasNvdKey = !!getNvdApiKey();
1433
- if (options.nvd && !offline && !hasNvdKey) {
1452
+ if (options.nvd && !offline && !hasNvdKey && !options.vigievulnProxy) {
1434
1453
  ui.warn(chalk.yellow("No NVD API key — enrichment throttled to 5 req/30s (slow)."));
1435
1454
  ui.info(chalk.dim("Free & instant key: https://nvd.nist.gov/developers/request-an-api-key"));
1436
1455
  ui.info(chalk.dim("then: vigievuln --set-nvd-key <KEY>"));
@@ -1821,7 +1840,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
1821
1840
  filtered = cveMatches.filter(m => m.cpeFiltered).length;
1822
1841
  } catch (err) { ui.warn(`CPE refinement skipped: ${err.message}`); }
1823
1842
  const uniqueCves = new Set(cveMatches.map(m => m.cve?.id)).size;
1824
- st.done(`${uniqueCves} CVE${nvdAdded ? ` · +${nvdAdded} via CPE ranges` : ""}${filtered ? ` · ${filtered} false-positive(s) filtered` : ""}${hasNvdKey ? "" : " · no key (slow)"}`);
1843
+ st.done(`${uniqueCves} CVE${nvdAdded ? ` · +${nvdAdded} via CPE ranges` : ""}${filtered ? ` · ${filtered} false-positive(s) filtered` : ""}${hasNvdKey || options.vigievulnProxy ? "" : " · no key (slow)"}`);
1825
1844
  } catch (err) { st.fail(err.message); }
1826
1845
  }
1827
1846
  }