vigievuln 1.0.1 → 1.1.1

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +56 -8
  3. package/completions/vigievuln.bash +4 -1
  4. package/completions/vigievuln.zsh +3 -0
  5. package/lib/account-client.js +191 -0
  6. package/lib/account-session.js +436 -0
  7. package/lib/account-terms.js +13 -0
  8. package/lib/application-plugins/runner.js +73 -13
  9. package/lib/application-plugins/wordpress.js +10 -3
  10. package/lib/application-providers/live-snapshot.js +6 -1
  11. package/lib/application-providers/wordfence-client.js +70 -0
  12. package/lib/application-providers/wordfence-projection.js +76 -0
  13. package/lib/application-providers/wordfence-v3.js +22 -6
  14. package/lib/cache-archive.js +21 -23
  15. package/lib/cache-directory.js +77 -0
  16. package/lib/certfr.js +18 -3
  17. package/lib/cli-command-routing.js +49 -0
  18. package/lib/cli-project-commands.js +96 -0
  19. package/lib/cli-watch.js +111 -0
  20. package/lib/cms-snapshot-warm.js +11 -4
  21. package/lib/codecs/composer/registry.js +3 -3
  22. package/lib/codecs/composer/relations.js +18 -0
  23. package/lib/codecs/composer.codec.js +2 -0
  24. package/lib/codecs/go/parse.js +23 -9
  25. package/lib/codecs/go/registry.js +3 -3
  26. package/lib/codecs/go.codec.js +20 -3
  27. package/lib/codecs/maven.codec.js +20 -1
  28. package/lib/codecs/npm/collect.js +90 -6
  29. package/lib/codecs/npm/registry.js +3 -3
  30. package/lib/codecs/nuget/parse.js +5 -1
  31. package/lib/codecs/nuget/registry.js +3 -3
  32. package/lib/codecs/nuget.codec.js +2 -12
  33. package/lib/codecs/pypi/registry.js +3 -3
  34. package/lib/codecs/ruby/parse.js +3 -0
  35. package/lib/codecs/ruby/registry.js +3 -3
  36. package/lib/codecs/ruby/relations.js +62 -0
  37. package/lib/codecs/ruby.codec.js +4 -1
  38. package/lib/codecs/version-evidence.js +18 -0
  39. package/lib/config.js +1 -1
  40. package/lib/cve-download.js +1 -1
  41. package/lib/cve-match.js +4 -0
  42. package/lib/deps-descriptor.js +1 -1
  43. package/lib/epss.js +7 -3
  44. package/lib/euvd.js +21 -3
  45. package/lib/hash-id.js +1 -1
  46. package/lib/hosted-proxy.js +51 -0
  47. package/lib/kev.js +18 -2
  48. package/lib/nvd.js +5 -5
  49. package/lib/osv-db.js +2 -1
  50. package/lib/osv.js +4 -3
  51. package/lib/outdated.js +7 -6
  52. package/lib/packagist-audit.js +4 -4
  53. package/lib/project-client.js +132 -0
  54. package/lib/project-descriptor.js +30 -0
  55. package/lib/provenance.js +1 -1
  56. package/lib/providers/certfr.js +1 -0
  57. package/lib/providers/euvd.js +1 -0
  58. package/lib/providers/github.js +1 -0
  59. package/lib/providers/index.js +15 -5
  60. package/lib/providers/kev.js +1 -1
  61. package/lib/providers/wordfence.js +5 -1
  62. package/lib/proxy-cache.js +3 -3
  63. package/lib/resource-cache/engine.js +149 -20
  64. package/lib/resource-cache/fs-store.js +1 -1
  65. package/lib/resource-cache/validate.js +10 -3
  66. package/lib/resource-cache/wordfence.js +77 -0
  67. package/lib/retire.js +38 -17
  68. package/lib/source-health.js +6 -0
  69. package/lib/transitive.js +2 -2
  70. package/package.json +1 -1
  71. package/vigievuln.js +173 -64
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog — VigieVuln
2
2
 
3
+ ## [1.1.1] — Unreleased
4
+
5
+ - Review and explicitly accept the current service terms when a hosted account requires it.
6
+ - Refuse project descriptors larger than 500,000 UTF-8 bytes before upload.
7
+ - Document the renewable one-month free project watch and its expiry.
8
+
9
+ ## [1.1.0] — 2026-10-28
10
+
11
+ - Hosted proxy scans query CVE, KEV, EUVD and CERT-FR records by dependency or CVE instead of downloading bulk catalogues.
12
+ - Configure the official proxy persistently, sign in to create a proxy key, and reuse it for later scans.
13
+ - Preserve OSV pagination tokens through the proxy and identify stale responses in batches.
14
+ - Sign in and upload a reviewed project descriptor to monitor direct dependencies for high or critical vulnerabilities.
15
+ - Use `watch`, `scan`, `login`, `logout` and `whoami` as direct commands; `watch --export` prepares a local descriptor.
16
+ - Use targeted Wordfence results through the hosted proxy, with explicit warnings when cached data is stale.
17
+ - Limit GitHub release notes to the changelog section for the release version.
18
+
3
19
  ## [1.0.1] — 2026-10-26
4
20
 
5
21
  - Regenerated the HTML sample reports, terminal demo and report screenshot with VigieVuln branding.
package/README.md CHANGED
@@ -1,7 +1,8 @@
1
1
  <h1 align="center">
2
- VigieVuln
2
+ <img src="docs/assets/VigieVuln_Logo_sm.png" alt="VigieVuln" height="200">
3
3
  </h1>
4
4
 
5
+
5
6
  [![npm version](https://img.shields.io/npm/v/vigievuln.svg)](https://www.npmjs.com/package/vigievuln)
6
7
  [![npm downloads](https://img.shields.io/npm/dm/vigievuln.svg)](https://www.npmjs.com/package/vigievuln)
7
8
  [![license](https://img.shields.io/npm/l/vigievuln.svg)](LICENSE)
@@ -25,11 +26,13 @@ It scans **10 ecosystems + 9 CMS/Frameworks** (WordPress, Drupal, Symfony, Larav
25
26
  - **10 ecosystems in one pass**; Maven, Gradle, npm/Yarn/pnpm, Composer, PyPI, NuGet, Go, Ruby — plus **vendored JS**, committed **native binaries** (identified by checksum) and **embedded JARs** (fat-jars/war/ear, opened in-memory).
26
27
  - **No build tools**; No `mvn`/`gradle`/`npm`/`pip`/`dotnet`/`go`, no `node_modules/` → [how](docs/COMPARISON.md#how-its-autonomous-no-build-tools)
27
28
  - **CVE from multiple sources, merged & prioritised**; CVEProject + OSV.dev + Packagist security advisories + NVD, ranked **CISA KEV → EPSS → CVSS**.
28
- - **European references on every CVE**: ENISA **EUVD** id + ENISA's exploited flag, **GCVE** id, and the **CERT-FR** advisories citing it — bulk/incremental reads, no CVE id of your project is sent.
29
+ - **European references on every CVE**: ENISA **EUVD** id + ENISA's exploited flag, **GCVE** id, and the **CERT-FR** advisories citing it. Hosted proxy lookups send relevant CVE identifiers to the proxy.
29
30
  - **Beyond CVEs**; Report **EOL and out-of-active-support** frameworks, deprecated/abandoned/yanked, outdated, SPDX **licenses**, and **private/internal packages**
30
31
  - **CMS & frameworks audited as instances**; Symfony, Laravel, WordPress, Drupal, Joomla, PrestaShop, TYPO3, Magento/Adobe Commerce and SPIP with per-instance inventory (core, plugins, themes, bundles, components) → [the dedicated guide](docs/CMS-FRAMEWORKS.md)
31
32
  - **Crypto material**; committed **certificates**, **private vs public keys** across PEM/OpenSSH/PuTTY/PGP and JKS/PKCS#12 keystores.
32
33
  - **Air-gapped flow**; **zero network under `--offline`** → [Benchmark](docs/BENCHMARK.md) · [Air-gapped](#air-gapped-audits)
34
+ - **Hosted proxy with a verified account**; `--set-proxy-cache vigievuln` → [hosted proxy](docs/USAGE.md#hosted-vigievuln-proxy)
35
+ - **Project monitoring**; `vigievuln watch ./project --name 'My Project'` — one free project with up to **100 distinct direct dependency coordinates** → [monitoring guide](docs/USAGE.md#project-monitoring)
33
36
  - **Shared cache for a scanner fleet**; `vigievuln serve-cache` + `--proxy-cache` → [cache usage](docs/USAGE.md#shared-proxy-cache-server-serve-cache----proxy-cache)
34
37
  - **Supply-chain risk**; known-**malicious** advisories and suspected **typosquats** (`--typosquat`).
35
38
  - **Audit-grade**; every report carries a **provenance manifest** and a **Methodology & limitations** chapter; a `SHA256SUMS`;
@@ -43,8 +46,10 @@ It scans **10 ecosystems + 9 CMS/Frameworks** (WordPress, Drupal, Symfony, Larav
43
46
  ## Migration from fad-checker
44
47
 
45
48
  The npm package and primary command are now `vigievuln`. Existing `fad` and
46
- `fad-checker` commands remain aliases. The cache stays in `~/.fad-checker/` so
47
- existing credentials, warmed data and air-gapped workflows keep working.
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.
48
53
  `VIGIEVULN_ENV` and `.vigievuln-env.json` take precedence over their legacy
49
54
  `FAD_CHECKER_ENV` / `.fad-env.json` counterparts. Default report output is now
50
55
  `./vigievuln-report`; pass `-o` to retain another location.
@@ -53,11 +58,54 @@ existing credentials, warmed data and air-gapped workflows keep working.
53
58
 
54
59
  ```bash
55
60
  npm install -g vigievuln
56
- vigievuln -s ./my-project # → ./vigievuln-report/cve-report.html
61
+ vigievuln scan ./code # → ./vigievuln-report/cve-report.html
57
62
  ```
58
63
 
59
64
  A free [NVD API key](https://nvd.nist.gov/developers/request-an-api-key) (instant) gives 10× faster enrichment: `vigievuln --set-nvd-key YOUR_KEY`. A few common runs; full list via `vigievuln --help` or [docs/USAGE.md](docs/USAGE.md)
60
65
 
66
+ ### Monitor a project
67
+
68
+ Create and verify your [account](https://www.vigievuln.fr/account), then sign in and explicitly accept the [terms of service dated 2026-10-28](https://www.vigievuln.fr/terms) when prompted:
69
+
70
+ ```bash
71
+ vigievuln login
72
+ vigievuln whoami
73
+ vigievuln watch ./project --name 'My Project'
74
+ vigievuln project status
75
+ vigievuln logout
76
+ ```
77
+
78
+ `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.
79
+
80
+ 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.
81
+
82
+ 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.
83
+
84
+ 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.
85
+
86
+ To review the inventory before uploading, export it locally:
87
+
88
+ ```bash
89
+ vigievuln watch ./project --export fichier.json
90
+ ```
91
+
92
+ `--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.
93
+
94
+ 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).
95
+
96
+ Existing commands remain supported: `vigievuln -s ./code`, `auth login|status|logout`, `--prepare-project` and `project push`.
97
+
98
+ ### Official Vigie Vuln proxy cache
99
+
100
+ Configure the proxy once, then sign in with your verified [Vigie Vuln account](https://www.vigievuln.fr/account) when prompted:
101
+
102
+ ```bash
103
+ vigievuln --set-proxy-cache vigievuln # `default` selects the same official proxy
104
+ vigievuln scan ./code
105
+ ```
106
+
107
+ The selection and the proxy key created during proxy sign-in are saved in `~/.vigie-vuln/config.json` and reused on subsequent scans. This proxy key is separate from the account session used by `watch`. Alternatively, save an existing key with `vigievuln --set-proxy-cache-token <key>`, or provide it via `VIGIEVULN_PROXY_CACHE_TOKEN` (useful in CI). Remove the selection or key with `--unset-proxy-cache` or `--unset-proxy-cache-token`. `--proxy-cache <url>` overrides the saved selection for one scan. The hosted proxy receives requested package coordinates and CVE identifiers; it does not receive your source code. [Proxy documentation](docs/USAGE.md#hosted-vigievuln-proxy).
108
+
61
109
  ### Interactive HTML samples
62
110
 
63
111
  - **[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.
@@ -158,12 +206,12 @@ vigievuln doesn't just read the `composer.json` under a WordPress or Drupal site
158
206
  | **SPIP** | core (`$spip_version_branche` in `ecrire/inc_version.php`), dist plugins (`paquet.xml`), user plugins (`paquet.xml`/legacy `plugin.xml`) | **NVD product CVEs** (`cpe:2.3:a:spip:spip`) — the only machine-readable SPIP source; plugins stay honestly not-qualified |
159
207
  | **Joomla / Magento (Adobe Commerce)** | core, extensions/modules, themes | no machine-readable publisher feed exists; components locked as Composer packages read as covered by the **dependency lanes**, the rest stays honestly **not qualified**. A Magento source distribution reports its exact version from the root `composer.json` |
160
208
 
161
- Every advisory snapshot a live lane fetches is stamped and cached in `~/.fad-checker/advisory-snapshots/`, carried by `--export-cache`/`--import-cache`, **warmed from the air-gapped descriptor itself** by `--import-anonymized`, and reused automatically offline — the Wordfence API key never travels to the enclave. Private/custom components are inventoried separately and never sent to any publisher. → **[the dedicated guide](docs/CMS-FRAMEWORKS.md)** · [application usage](docs/USAGE.md#application-inventory-experimental)
209
+ Every advisory snapshot a live lane fetches is stamped and cached in `~/.vigie-vuln/advisory-snapshots/`, carried by `--export-cache`/`--import-cache`, **warmed from the air-gapped descriptor itself** by `--import-anonymized`, and reused automatically offline — the Wordfence API key never travels to the enclave. Private/custom components are inventoried separately and never sent to any publisher. → **[the dedicated guide](docs/CMS-FRAMEWORKS.md)** · [application usage](docs/USAGE.md#application-inventory-experimental)
162
210
 
163
211
  ## Air-gapped audits
164
212
 
165
213
  > **Zero-data-sent guarantee.** Under `--offline`, vigievuln makes **no network calls
166
- > whatsoever**; it reads only the warmed `~/.fad-checker/` caches and never transmits a
214
+ > whatsoever**; it reads only the warmed `~/.vigie-vuln/` caches and never transmits a
167
215
  > dependency, path or finding off the machine. It is regression-tested
168
216
  > (`test/offline-guarantee.test.js`, a tripwire fetcher that throws if touched) and
169
217
  > auditor-reproducible: `unshare -rn node vigievuln.js -s ./proj --offline …` runs it in a
@@ -193,7 +241,7 @@ vigievuln -s ./proj -e "^(client|internal)\." --export-anonymized deps.json
193
241
  vigievuln --import-anonymized deps.json # scans coordinates → OSV/NVD/CVE/registry/EOL + retire signatures
194
242
  # + warms the CMS advisory snapshots (Drupal/PrestaShop/TYPO3 feeds,
195
243
  # WP checksums per core version, Wordfence when a key is set)
196
- vigievuln --export-cache fad-cache.tar.gz # bundle the warmed ~/.fad-checker/
244
+ vigievuln --export-cache fad-cache.tar.gz # bundle the warmed ~/.vigie-vuln/
197
245
 
198
246
  # ── Phase 3; OFFLINE (audited machine): full report, all local context ──
199
247
  vigievuln --import-cache fad-cache.tar.gz # merged into the enclave's own cache
@@ -6,11 +6,14 @@ _fad_check_complete() {
6
6
  COMPREPLY=()
7
7
  cur="${COMP_WORDS[COMP_CWORD]}"
8
8
  prev="${COMP_WORDS[COMP_CWORD-1]}"
9
- opts="--src --target --exclude --verbose --no-report --no-transitive --no-all-libs --no-osv --no-nvd --no-epss --no-kev --licenses --no-retire --retire-refresh --report-output --report-html --report-doc --report-xlsx --report-sbom --report-csaf --report-json --report-sarif --fail-on --fail-on-new --baseline --no-checksums --ignore --vex --ignore-test --cve-refresh --cve-offline --snyk --transitive-depth --offline --ecosystem --no-maven --no-npm --no-yarn --no-nuget --no-composer --no-pypi --no-go --no-ruby --no-jars --no-binaries --no-certs --cert-expiry-days --retries --no-nvd-mirror --eol-support --no-eol --no-js --set-nvd-key --show-config --completion --help --version --disable --activate --report --help-all -s -t -e -h -v -d -a -r -o"
9
+ opts="--vigievuln-proxy --proxy-cache --proxy-cache-token --src --target --exclude --verbose --no-report --no-transitive --no-all-libs --no-osv --no-nvd --no-epss --no-kev --licenses --no-retire --retire-refresh --report-output --report-html --report-doc --report-xlsx --report-sbom --report-csaf --report-json --report-sarif --fail-on --fail-on-new --baseline --no-checksums --ignore --vex --ignore-test --cve-refresh --cve-offline --snyk --transitive-depth --offline --ecosystem --no-maven --no-npm --no-yarn --no-nuget --no-composer --no-pypi --no-go --no-ruby --no-jars --no-binaries --no-certs --cert-expiry-days --retries --no-nvd-mirror --eol-support --no-eol --no-js --set-nvd-key --show-config --completion --help --version --disable --activate --report --help-all -s -t -e -h -v -d -a -r -o"
10
10
  case "$prev" in
11
11
  --src|-s|--target|-t|--report-output|-o)
12
12
  COMPREPLY=( $(compgen -d -- "$cur") )
13
13
  return 0 ;;
14
+ --vigievuln-proxy)
15
+ COMPREPLY=( $(compgen -W "fr com" -- "$cur") )
16
+ return 0 ;;
14
17
  --ecosystem)
15
18
  COMPREPLY=( $(compgen -W "auto all maven npm yarn nuget composer pypi" -- "$cur") )
16
19
  return 0 ;;
@@ -3,6 +3,9 @@
3
3
  _fad_check() {
4
4
  local -a opts
5
5
  opts=(
6
+ '--vigievuln-proxy[Use the hosted proxy]::domain:(fr com)'
7
+ '--proxy-cache[Shared proxy URL]:url:'
8
+ '--proxy-cache-token[Proxy authentication key]:token:'
6
9
  '-s[root directory containing pom.xml files]:directory:_directories'
7
10
  '--src[root directory containing pom.xml files]:directory:_directories'
8
11
  '-t[output directory]:directory:_directories'
@@ -0,0 +1,191 @@
1
+ 'use strict';
2
+
3
+ const { createAccountSessionStore, validateAccountSession } = require('./account-session');
4
+
5
+ const ACCOUNT_ORIGIN = 'https://www.vigievuln.fr';
6
+ const DEFAULT_TIMEOUT_MS = 15000;
7
+ const MAX_RESPONSE_BYTES = 64 * 1024;
8
+
9
+ class AccountClientError extends Error {
10
+ constructor(code, message, status) {
11
+ super(message);
12
+ this.name = 'AccountClientError';
13
+ this.code = code;
14
+ if (status !== undefined) this.status = status;
15
+ }
16
+ }
17
+
18
+ const invalidResponse = () => new AccountClientError('INVALID_RESPONSE', 'Invalid account API response.');
19
+ const isAccount = value => value && typeof value === 'object' && !Array.isArray(value) &&
20
+ typeof value.id === 'string' && value.id.length > 0 && typeof value.email === 'string' && value.email.length > 0;
21
+ function readTerms(value) {
22
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
23
+ typeof value.version !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(value.version) ||
24
+ typeof value.documentUrl !== 'string' || value.documentUrl.length > 2048 ||
25
+ /[\x00-\x20\x7f]/.test(value.documentUrl) || typeof value.accepted !== 'boolean') throw invalidResponse();
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 ||
29
+ url.pathname !== '/terms/' + value.version || url.search || url.hash ||
30
+ ![url.pathname, ACCOUNT_ORIGIN + url.pathname].includes(value.documentUrl)) throw invalidResponse();
31
+ return { version: value.version, url: url.href, accepted: value.accepted };
32
+ }
33
+
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.
37
+ * login({email,password}) -> {account,expiresAt}; me() -> {account};
38
+ * logout() -> {revoked}. logout always clears local storage, including on a
39
+ * remote error, which is still reported (revocation is then unconfirmed).
40
+ * The password exists only in the in-flight request, never in the store.
41
+ */
42
+ function createAccountClient({ fetcher = globalThis.fetch, now = Date.now,
43
+ sessionStore = createAccountSessionStore({ now }), timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
44
+ if (typeof fetcher !== 'function' || !Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
45
+ throw new AccountClientError('INVALID_OPTIONS', 'Invalid account transport or timeout.');
46
+ }
47
+
48
+ async function request(route, method, body, token) {
49
+ const controller = new AbortController();
50
+ let timer;
51
+ let response;
52
+ const deadline = new Promise((_, reject) => {
53
+ timer = setTimeout(() => {
54
+ reject(new AccountClientError('TIMEOUT', 'Account API request timed out.'));
55
+ controller.abort();
56
+ }, timeoutMs);
57
+ });
58
+ const operation = async () => {
59
+ response = await fetcher(ACCOUNT_ORIGIN + '/v1/accounts/' + route, {
60
+ method, redirect: 'error', credentials: 'omit', cache: 'no-store',
61
+ headers: { accept: 'application/json', ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
62
+ ...(token ? { authorization: 'Bearer ' + token } : {}) },
63
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}), signal: controller.signal,
64
+ });
65
+ if (controller.signal.aborted) {
66
+ if (response.body && !response.body.locked) void response.body.cancel().catch(() => {});
67
+ throw new AccountClientError('TIMEOUT', 'Account API request timed out.');
68
+ }
69
+ // Also reject an injected transport that reports a redirect/followed URL.
70
+ if (response.redirected || (response.status >= 300 && response.status < 400) ||
71
+ (response.url && response.url !== ACCOUNT_ORIGIN + '/v1/accounts/' + route)) {
72
+ throw new AccountClientError('REDIRECT_REFUSED', 'Account API redirects are forbidden.');
73
+ }
74
+ if (!response.ok) {
75
+ const code = ({ 401: 'UNAUTHORIZED', 403: 'FORBIDDEN', 429: 'RATE_LIMITED' })[response.status] || 'HTTP_ERROR';
76
+ throw new AccountClientError(code, `Account API request failed (HTTP ${response.status}).`, response.status);
77
+ }
78
+ if (!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type') || '') || !response.body) throw invalidResponse();
79
+ const reader = response.body.getReader();
80
+ const cancel = () => { void reader.cancel().catch(() => {}); };
81
+ controller.signal.addEventListener('abort', cancel, { once: true });
82
+ const chunks = [];
83
+ let size = 0;
84
+ try {
85
+ while (true) {
86
+ const { value, done } = await reader.read();
87
+ if (done) break;
88
+ size += value.byteLength;
89
+ if (size > MAX_RESPONSE_BYTES) throw invalidResponse();
90
+ chunks.push(Buffer.from(value));
91
+ }
92
+ } finally {
93
+ // Do not allow cancellation of an injected stream to hold up the timeout.
94
+ controller.signal.removeEventListener('abort', cancel);
95
+ cancel();
96
+ reader.releaseLock();
97
+ }
98
+ let data;
99
+ try { data = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
100
+ catch { throw invalidResponse(); }
101
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw invalidResponse();
102
+ return data;
103
+ };
104
+ try { return await Promise.race([operation(), deadline]); }
105
+ catch (error) {
106
+ if (error instanceof AccountClientError) throw error;
107
+ // Fetch/JSON errors can include a URL, credentials or response contents.
108
+ throw new AccountClientError('NETWORK_ERROR', 'Unable to reach the account API.');
109
+ } finally {
110
+ clearTimeout(timer);
111
+ controller.abort();
112
+ if (response?.body && !response.body.locked) void response.body.cancel().catch(() => {});
113
+ }
114
+ }
115
+
116
+ async function currentSession() {
117
+ const session = await sessionStore.read();
118
+ if (!session) throw new AccountClientError('NOT_AUTHENTICATED', 'No account session. Sign in first.');
119
+ return validateAccountSession(session, now());
120
+ }
121
+
122
+ async function login(credentials = {}) {
123
+ const { email, password } = credentials || {};
124
+ if (typeof email !== 'string' || !email.trim() || email.length > 254 ||
125
+ typeof password !== 'string' || !password || Buffer.byteLength(password, 'utf8') > 512) {
126
+ throw new AccountClientError('INVALID_CREDENTIALS', 'An email and password are required.');
127
+ }
128
+ const data = await request('login', 'POST', { email, password });
129
+ let session;
130
+ try { session = validateAccountSession(data, now()); }
131
+ catch { throw invalidResponse(); }
132
+ if (data.tokenType !== 'Bearer' || !isAccount(data.account)) throw invalidResponse();
133
+ const terms = readTerms(data.account.terms);
134
+ try { await sessionStore.write(session); }
135
+ catch (error) {
136
+ // Avoid leaving a newly issued session alive when local persistence fails.
137
+ try { await request('logout', 'POST', {}, session.token); } catch { /* expires server-side */ }
138
+ throw error;
139
+ }
140
+ return { account: data.account, expiresAt: session.expiresAt, ...(terms && { terms }) };
141
+ }
142
+
143
+ async function me() {
144
+ const session = await currentSession();
145
+ try {
146
+ const data = await request('me', 'GET', undefined, session.token);
147
+ if (!isAccount(data.account)) throw invalidResponse();
148
+ const terms = readTerms(data.account.terms);
149
+ return { account: data.account, ...(terms && { terms }) };
150
+ } catch (error) {
151
+ if (error.code === 'UNAUTHORIZED') await sessionStore.clear();
152
+ throw error;
153
+ }
154
+ }
155
+
156
+ async function acceptTerms(version) {
157
+ if (typeof version !== 'string' || !version || version.length > 200 || /[\x00-\x1f\x7f]/.test(version)) {
158
+ throw new AccountClientError('INVALID_TERMS', 'A valid terms version is required.');
159
+ }
160
+ const session = await currentSession();
161
+ const data = await request('terms', 'POST', { termsVersion: version, accepted: true }, session.token);
162
+ if (!isAccount(data.account)) throw invalidResponse();
163
+ const terms = readTerms(data.account.terms);
164
+ if (!terms || !terms.accepted || terms.version !== version) throw invalidResponse();
165
+ return { terms };
166
+ }
167
+
168
+ async function createProxyKey() {
169
+ const session = await currentSession();
170
+ const data = await request('proxy-keys', 'POST', { name: 'VigieVuln CLI' }, session.token);
171
+ if (typeof data?.key?.token !== 'string' || !data.key.token) throw invalidResponse();
172
+ return { token: data.key.token };
173
+ }
174
+
175
+ async function logout() {
176
+ try {
177
+ const stored = await sessionStore.read();
178
+ if (!stored) return { revoked: 0 };
179
+ let session;
180
+ try { session = validateAccountSession(stored, now()); }
181
+ catch (error) { if (error.code === 'SESSION_EXPIRED') return { revoked: 0 }; throw error; }
182
+ const data = await request('logout', 'POST', {}, session.token);
183
+ if (!Number.isSafeInteger(data.revoked) || data.revoked < 0) throw invalidResponse();
184
+ return { revoked: data.revoked };
185
+ } finally { await sessionStore.clear(); }
186
+ }
187
+
188
+ return { login, logout, me, createProxyKey, acceptTerms };
189
+ }
190
+
191
+ module.exports = { ACCOUNT_ORIGIN, DEFAULT_TIMEOUT_MS, createAccountClient, AccountClientError };