From 03e17206fcc62fa50d32fa845e23908b78a5e488 Mon Sep 17 00:00:00 2001 From: AjayBThorat-20 Date: Thu, 29 Oct 2026 23:13:06 +0530 Subject: [PATCH] feat: check the whole dependency tree, add `devcompass why`, drop npm-check-updates - A dependency graph built from package-lock.json alone (npm; pnpm/yarn/bun, no lockfile or lockfileVersion 1 report incomplete). Edges are resolved from the lockfile's install paths, so the graph is complete before `npm install` and links optional platform packages to their own nested dependencies. - The OSV check covers every installed name@version in that graph, not just direct dependencies (falls back to direct ones without a usable graph). On express@4.17.1 + lodash this finds 7 vulnerable packages instead of 4. OSV queries are chunked, 200 packages per request, 4 in flight. - `devcompass why ` prints every path from the project to each installed version of a package. - The outdated check uses the registry client instead of npx npm-check-updates (-6.3 MB). The cache now keeps the published version list, so `wanted` is the highest version the declared range allows. - Lockfile-only fixes for new follow-redirects and zod advisories. --- CHANGELOG.md | 9 + README.md | 13 ++ bin/devcompass.js | 1 + llms.txt | 1 + package-lock.json | 27 +-- package.json | 1 - src/cli/commands/why.cmd.js | 58 +++++ src/core/graph/index.js | 199 +++++++++++++++++ src/core/graph/why.js | 61 +++++ .../analyze/collectors/cve.collector.js | 6 +- .../collectors/dependency.collector.js | 107 +++++---- src/features/analyze/collectors/index.js | 4 +- src/features/analyze/index.js | 15 +- src/features/cve/osv.client.js | 18 ++ src/features/cve/vulnerability-checker.js | 60 +++-- src/shared/services/registry-client.js | 4 +- test/unit/analyze-read-only.test.js | 30 --- test/unit/dependency-graph.test.js | 211 ++++++++++++++++++ test/unit/outdated-collector.test.js | 160 +++++++++++++ test/unit/whole-tree-cve.test.js | 76 +++++++ test/unit/why.test.js | 77 +++++++ 21 files changed, 1027 insertions(+), 111 deletions(-) create mode 100644 src/cli/commands/why.cmd.js create mode 100644 src/core/graph/index.js create mode 100644 src/core/graph/why.js create mode 100644 test/unit/dependency-graph.test.js create mode 100644 test/unit/outdated-collector.test.js create mode 100644 test/unit/whole-tree-cve.test.js create mode 100644 test/unit/why.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a98b3e..8d25922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `devcompass why `: shows every path from the project to an installed package, so a vulnerable or outdated transitive dependency like `qs` nested under `express` is traceable back to what pulled it in. +- A dependency graph built from `package-lock.json` (npm only — pnpm/yarn/bun, a missing lockfile, or a lockfileVersion 1 file report `incomplete` instead of silently returning an empty graph). It correctly distinguishes several installed versions of one package at different nesting depths (e.g. a direct `qs@6.9.0` alongside `express`'s own nested `qs@6.7.0`), and is built from the lockfile alone, so it is complete before `npm install` has run. - `devcompass clean` has a `-p, --path ` option, like every other command — it could only ever operate on the current directory. - Every finding now carries a `ruleId` (e.g. `vuln`, `typosquat`, `outdated/major`, `unused`), a `confidence` (`high`/`medium`/`low` — heuristics like unused/typosquat are never `high`), and the full list of `advisoryIds` it merged (previously only the first GHSA/CVE id was kept, though a count was computed and silently discarded). A finding's `id` is now `:@[:]` instead of `@`, so two different findings for the same package no longer share an id. - `analyze --json`'s `metadata` has a `scanIncomplete` object with an entry per collector, alongside the existing `cveScanIncomplete`/`securityScanIncomplete`/... flags. @@ -16,6 +18,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **The OSV check now covers the whole dependency tree, not just direct dependencies.** Every installed `name@version` in the lockfile is checked, so a vulnerability in a transitive package is found on its own rather than only when npm audit happens to also flag it (npm audit's results are filtered to HIGH/CRITICAL). On a project whose only dependencies are `express@4.17.1` and `lodash`, this finds 7 vulnerable packages instead of 4. Projects without a usable `package-lock.json` keep the previous direct-dependency check. +- OSV queries are sent 200 packages per request (4 in flight) instead of all in one request — needed now that whole trees are checked, and one slow or rejected chunk no longer fails every package in the scan. +- **`npm-check-updates` is gone** (−6.3 MB). The outdated check uses the npm registry client DevCompass already ships, plus `semver`. `wanted` is now the highest published version the declared range allows (e.g. `4.1.2` for `chalk@^4.0.0`); npm-check-updates always reported the latest version, even across a major the range doesn't allow. - The four separate severity/priority tables (`severity.js`, `issue.model.js`, `data/priorities.json`, and the inline tables in `console-formatter.js`) are down to one, `core/utils/severity.js`; everything else imports from it. They had already drifted out of sync with each other. - Collectors run from one registry (`src/features/analyze/collectors/index.js`) instead of a hardcoded list in `analyze`'s core — a new check is one collector file plus one entry, and its "scan incomplete" message comes from that entry. - Test coverage is now measured over every file in `src/` (except the browser dashboard) rather than only the files a test happens to load, which had been inflating the number. The honest figure is ~29%, so the CI floor is 25% instead of the previous, misleading 60%. @@ -43,6 +48,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `cve.collector.js` kept only the first advisory id per package (it counted the rest and discarded them); every advisory id now reaches the finding. - An ecosystem alert whose suggested fix is free text no longer reads "Update to Consider alternatives…", and isn't marked as a safe fix. +### Security + +- `follow-redirects` 1.16.0 → 1.16.1 and `zod` 4.3.6 → 4.6.7 for newly published advisories (lockfile-only). + ## [4.1.9] - 2026-10-06 ### Fixed diff --git a/README.md b/README.md index 6d12cca..82098c2 100644 --- a/README.md +++ b/README.md @@ -313,6 +313,19 @@ devcompass fix undo ### Visualization +#### `why` - Why Is This Package Installed? + +Show every path from your project to an installed package — useful when a vulnerable or outdated package is a transitive dependency you never declared. + +```bash +devcompass why qs +# qs@6.7.0 (2 paths) +# my-app → express@4.17.1 → body-parser@1.19.0 → qs@6.7.0 +# my-app → express@4.17.1 → qs@6.7.0 +``` + +It reads `package-lock.json` only (npm; pnpm/yarn/bun lockfiles aren't supported yet), so it works before `npm install` has run. Each installed version of the package is listed separately. + #### `graph` - Dependency Graph Visualization Generate interactive dependency graphs with multiple layouts and filters. diff --git a/bin/devcompass.js b/bin/devcompass.js index 50d8bae..9715f09 100755 --- a/bin/devcompass.js +++ b/bin/devcompass.js @@ -29,6 +29,7 @@ require('../src/cli/commands/llm.cmd')(program); require('../src/cli/commands/ai.cmd')(program); require('../src/cli/commands/config.cmd')(program); require('../src/cli/commands/clean.cmd')(program); +require('../src/cli/commands/why.cmd')(program); if (process.argv.length === 2) { (async () => { diff --git a/llms.txt b/llms.txt index de89014..b776d9f 100644 --- a/llms.txt +++ b/llms.txt @@ -30,6 +30,7 @@ DevCompass is a complement to `npm audit` and Dependabot for teams that also wan - `devcompass analyze` — Full dependency analysis: security, health score, license, unused/outdated packages. Flags: `--deep` (all issues, default shows top 3), `--json`, `--silent`, `--ci`, `--ci --threshold 8.0`. Health score bands: 9.0-10.0 excellent, 8.0-8.9 good, 6.0-7.9 needs attention, 4.0-5.9 poor, 0.0-3.9 critical. - `devcompass cve` — CVE database management. `cve key --set --api-key ` / `cve key` (status) / `cve key --remove`; `cve test` (test NVD connection); `cve cache --stats` / `cve cache --clear`. - `devcompass fix` — Automated issue resolution with risk classification (safe/moderate/risky), preview (including a live `package.json` diff), automatic backup before changes, interactive confirmation, and rollback support. Supports `--dry-run`. `--migrate-syntax` additionally rewrites source call-sites broken by a major-version update (built-in codemod, falling back to your configured AI provider), snapshotting every touched file; `devcompass fix undo` reverts the most recent `--migrate-syntax` run. +- `devcompass why ` — Every path from the project to an installed package, from package-lock.json (works before `npm install`). - `devcompass graph` — Interactive dependency graph, 5 layouts: Tree, Force-directed, Radial, Conflict, Analytics. Real-time filtering (vulnerable/outdated/unused), dark/light themes, export to PNG/JSON/HTML. Flag: `--open`. - `devcompass snapshot` — Save/manage point-in-time dependency state snapshots (`snapshot save`, etc.), stored in a local SQLite database. - `devcompass compare` — Side-by-side diff between two snapshots: `devcompass compare `. diff --git a/package-lock.json b/package-lock.json index 044c592..113b89a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,6 @@ "cross-spawn": "^7.0.6", "d3": "^7.8.5", "knip": "^6.12.2", - "npm-check-updates": "^20.0.0", "open": "^11.0.0", "ora": "5.4.1", "p-limit": "^3.1.0", @@ -1809,9 +1808,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", + "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", "funding": [ { "type": "individual", @@ -2481,20 +2480,6 @@ "node": ">=10" } }, - "node_modules/npm-check-updates": { - "version": "20.0.2", - "resolved": "https://registry.npmjs.org/npm-check-updates/-/npm-check-updates-20.0.2.tgz", - "integrity": "sha512-nvbcXiprjMOoSX0FCHC41kjpZhNFURV53KMU0MMa0U10RPHeoHpiilMg2P8g9NLSQoo0umSH77tUqHWTOH3w7A==", - "license": "Apache-2.0", - "bin": { - "ncu": "build/cli.js", - "npm-check-updates": "build/cli.js" - }, - "engines": { - "node": ">=20.0.0", - "npm": ">=8.12.1" - } - }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -3394,9 +3379,9 @@ } }, "node_modules/zod": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", - "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/package.json b/package.json index 45c8c2b..3d80bfc 100644 --- a/package.json +++ b/package.json @@ -71,7 +71,6 @@ "cross-spawn": "^7.0.6", "d3": "^7.8.5", "knip": "^6.12.2", - "npm-check-updates": "^20.0.0", "open": "^11.0.0", "ora": "5.4.1", "p-limit": "^3.1.0", diff --git a/src/cli/commands/why.cmd.js b/src/cli/commands/why.cmd.js new file mode 100644 index 0000000..0d06c5c --- /dev/null +++ b/src/cli/commands/why.cmd.js @@ -0,0 +1,58 @@ +// src/cli/commands/why.cmd.js +// +// FT-06: `devcompass why ` — how did this package get into the +// dependency tree, and is it vulnerable? + +const chalk = require('chalk'); +const fs = require('fs'); +const path = require('path'); + +module.exports = function registerWhyCommand(program) { + program + .command('why ') + .description('Show how a package got into the dependency tree') + .option('-p, --path ', 'Project path', process.cwd()) + .action(async (packageName, options) => { + const projectPath = options.path; + try { + const { loadDependencyGraph } = require('../../core/graph'); + const { why } = require('../../core/graph/why'); + + const graph = await loadDependencyGraph(projectPath); + + if (graph.incomplete) { + console.error(chalk.yellow(`\n⚠️ ${graph.incompleteReason}\n`)); + process.exitCode = 1; + return; + } + + const results = why(graph, packageName); + if (results.length === 0) { + console.log(chalk.yellow(`\n"${packageName}" isn't in the installed dependency tree.\n`)); + return; + } + + const packageJson = JSON.parse(fs.readFileSync(path.join(projectPath, 'package.json'), 'utf8')); + const projectName = packageJson.name || path.basename(projectPath); + + console.log(''); + for (const { node, paths } of results) { + console.log(chalk.bold.cyan(`${node.id} (${paths.length} path${paths.length === 1 ? '' : 's'})`) + (node.direct ? chalk.gray(' [direct dependency]') : '')); + paths.forEach(trail => { + const printable = [projectName, ...trail.slice(1)].join(chalk.gray(' → ')); + console.log(` ${printable}`); + }); + if (paths.length === 0 && !node.direct) { + console.log(chalk.gray(' (no path found from the root — check the lockfile for an inconsistency)')); + } + console.log(''); + } + + console.log(chalk.gray('Run `devcompass analyze --deep` for vulnerability/license findings on these packages, and `devcompass fix --dry-run` for suggested overrides.\n')); + } catch (error) { + console.error(chalk.red('\n❌ why failed:'), error.message); + if (process.env.DEBUG) console.error(error.stack); + process.exitCode = 1; + } + }); +}; diff --git a/src/core/graph/index.js b/src/core/graph/index.js new file mode 100644 index 0000000..1a82178 --- /dev/null +++ b/src/core/graph/index.js @@ -0,0 +1,199 @@ +// src/core/graph/index.js +// +// AR-01: one dependency graph, built from the lockfile, that every collector +// can read from instead of each re-deriving its own partial view (the OSV +// check only covering direct dependencies, the dashboard's graph only +// looking up top-level node_modules/ and getting nested versions +// wrong, "unknown" versions when a collector didn't resolve one itself). +// +// Deliberately dependency-free: @npmcli/arborist (npm's own resolver, the +// obvious library choice) pulls in ~115 packages / 24 MB. Edges are resolved +// from package-lock.json alone — its install paths already encode the +// node_modules layout — so the graph is complete even before `npm install` +// / `npm ci` has run, and never reads the disk beyond the lockfile. +// +// npm only for now — pnpm/yarn/bun need their own lockfile parsers (not +// implemented; see incomplete/incompleteReason below). + +const fs = require('fs'); +const path = require('path'); + +/** + * @typedef {object} PackageNode + * @property {string} id "name@version" + * @property {string} name + * @property {string} version + * @property {string[]} paths lockfile install paths, e.g. ["node_modules/express/node_modules/qs"] + * @property {boolean} direct declared in the root package.json + * @property {boolean} dev + * @property {boolean} optional + * @property {boolean} hasInstallScript + * @property {string|null} license + */ + +function detectPackageManager(projectPath) { + if (fs.existsSync(path.join(projectPath, 'package-lock.json'))) return 'npm'; + if (fs.existsSync(path.join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm'; + if (fs.existsSync(path.join(projectPath, 'yarn.lock'))) return 'yarn'; + if (fs.existsSync(path.join(projectPath, 'bun.lock')) || fs.existsSync(path.join(projectPath, 'bun.lockb'))) return 'bun'; + return null; +} + +function packageNameFromPath(pkgPath) { + const idx = pkgPath.lastIndexOf('node_modules/'); + return idx === -1 ? pkgPath : pkgPath.slice(idx + 'node_modules/'.length); +} + +// Which lockfile entry `depName` resolves to when required from the package +// installed at `fromKey` ('' for the project root): Node's own lookup — +// nearest node_modules wins, walking up — applied to the lockfile's install +// paths. A package that isn't installed on this platform (an optional, +// OS-specific binary) still resolves to its own nested copy, where walking +// the real node_modules would have climbed to an unrelated top-level one. +function resolveInLockfile(packages, fromKey, depName) { + let base = fromKey; + while (true) { + const candidate = base ? `${base}/node_modules/${depName}` : `node_modules/${depName}`; + if (packages[candidate]) return candidate; + if (!base) return null; + const idx = base.lastIndexOf('/node_modules/'); + base = idx === -1 ? '' : base.slice(0, idx); + } +} + +function loadNpmGraph(lock) { + const packages = lock.packages || {}; + const nodes = new Map(); // id ("name@version") -> PackageNode + const pathKeyToNodeId = new Map(); // lockfile path key -> node id, for edge resolution + const roots = []; + + const rootEntry = packages[''] || {}; + const rootDirect = new Set(Object.keys({ + ...(rootEntry.dependencies || {}), + ...(rootEntry.devDependencies || {}), + ...(rootEntry.optionalDependencies || {}) + })); + + for (const [key, entry] of Object.entries(packages)) { + if (key === '' || !entry || !key.includes('node_modules/')) continue; + const name = packageNameFromPath(key); + if (!name || !entry.version) continue; + + const id = `${name}@${entry.version}`; + // A direct dependency's node_modules entry sits right at the top level + // (node_modules/), never nested under another package. + const isTopLevel = key === `node_modules/${name}`; + + if (!nodes.has(id)) { + nodes.set(id, { + id, + name, + version: entry.version, + paths: [], + direct: isTopLevel && rootDirect.has(name), + dev: !!entry.dev, + optional: !!entry.optional, + hasInstallScript: !!entry.hasInstallScript, + license: entry.license || null + }); + } + const node = nodes.get(id); + node.paths.push(key); + if (isTopLevel && rootDirect.has(name)) node.direct = true; + // dev/optional are per-install-location in npm's own model; a package + // is only dev-only/optional-only overall if every location it appears + // at agrees (a prod dep that's *also* pulled in by a devDependency is + // still a prod dep). + if (!entry.dev) node.dev = false; + if (!entry.optional) node.optional = false; + + pathKeyToNodeId.set(key, id); + if (isTopLevel && rootDirect.has(name)) roots.push(id); + } + + // Nodes are deduplicated by name@version, but a node can have several + // physical install locations (paths.length > 1) — without deduping here + // too, each of those locations would independently produce the same + // logical (fromId -> toId) edge, and a path search downstream (why.js) + // would then "discover" the identical path once per redundant edge. + const edgeKeys = new Set(); + const edges = []; + function addEdge(fromId, toId) { + if (!toId || toId === fromId) return; + const key = `${fromId}->${toId}`; + if (edgeKeys.has(key)) return; + edgeKeys.add(key); + edges.push([fromId, toId]); + } + + for (const [key, entry] of Object.entries(packages)) { + if (key === '' || !entry) continue; + const fromId = pathKeyToNodeId.get(key); + if (!fromId) continue; + + const declaredDeps = { + ...(entry.dependencies || {}), + ...(entry.optionalDependencies || {}) + }; + for (const depName of Object.keys(declaredDeps)) { + const resolvedKey = resolveInLockfile(packages, key, depName); + if (resolvedKey) addEdge(fromId, pathKeyToNodeId.get(resolvedKey)); + } + } + + // The root package.json's own declared deps -> edges from a synthetic "root" id. + for (const depName of rootDirect) { + const resolvedKey = resolveInLockfile(packages, '', depName); + if (resolvedKey) addEdge('root', pathKeyToNodeId.get(resolvedKey)); + } + + return { packageManager: 'npm', nodes, edges, roots }; +} + +/** + * @param {string} projectPath + * @returns {Promise<{packageManager: string|null, nodes: Map, edges: Array<[string,string]>, roots: string[], incomplete?: boolean, incompleteReason?: string}>} + */ +async function loadDependencyGraph(projectPath) { + const packageManager = detectPackageManager(projectPath); + + if (packageManager === null) { + return { packageManager: null, nodes: new Map(), edges: [], roots: [], incomplete: true, incompleteReason: 'No lockfile found' }; + } + + if (packageManager !== 'npm') { + return { + packageManager, + nodes: new Map(), + edges: [], + roots: [], + incomplete: true, + incompleteReason: `${packageManager} lockfiles aren't supported yet — only npm's package-lock.json is` + }; + } + + const lockPath = path.join(projectPath, 'package-lock.json'); + let lock; + try { + lock = JSON.parse(fs.readFileSync(lockPath, 'utf8')); + } catch (error) { + return { packageManager, nodes: new Map(), edges: [], roots: [], incomplete: true, incompleteReason: `Could not read package-lock.json: ${error.message}` }; + } + + if (!lock.packages) { + // lockfileVersion 1 (npm <=6): a different, nested `dependencies` shape + // this parser doesn't read yet. + return { + packageManager, + nodes: new Map(), + edges: [], + roots: [], + incomplete: true, + incompleteReason: `package-lock.json is lockfileVersion ${lock.lockfileVersion || 1}, which this parser doesn't support yet (needs lockfileVersion 2 or 3)` + }; + } + + return loadNpmGraph(lock); +} + +module.exports = { loadDependencyGraph, detectPackageManager, resolveInLockfile }; diff --git a/src/core/graph/why.js b/src/core/graph/why.js new file mode 100644 index 0000000..29c11f3 --- /dev/null +++ b/src/core/graph/why.js @@ -0,0 +1,61 @@ +// src/core/graph/why.js +// +// FT-06: `devcompass why ` — how did this package get into the +// tree? Built on the dependency graph (AR-01). + +const MAX_PATHS_PER_NODE = 10; +const MAX_DEPTH = 20; // guards against a malformed/cyclic lockfile + +// Every path from 'root' to `targetId`, as arrays of node ids +// (['root', 'express@4.17.1', 'qs@6.7.0']), depth-first with a visited set +// per path so a cycle can't loop forever. +function findPaths(edges, targetId) { + const adjacency = new Map(); + for (const [from, to] of edges) { + if (!adjacency.has(from)) adjacency.set(from, []); + adjacency.get(from).push(to); + } + + const paths = []; + + function walk(currentId, trail, visited) { + if (paths.length >= MAX_PATHS_PER_NODE) return; + if (trail.length > MAX_DEPTH) return; + + if (currentId === targetId && trail.length > 1) { + paths.push([...trail]); + return; + } + + const next = adjacency.get(currentId) || []; + for (const child of next) { + if (visited.has(child)) continue; // cycle guard + if (paths.length >= MAX_PATHS_PER_NODE) return; + visited.add(child); + trail.push(child); + walk(child, trail, visited); + trail.pop(); + visited.delete(child); + } + } + + walk('root', ['root'], new Set(['root'])); + return paths; +} + +/** + * @param {{nodes: Map, edges: Array<[string,string]>}} graph + * @param {string} packageName + * @returns {Array<{node: object, paths: string[][]}>} one entry per + * installed version of `packageName`, each with every path from root. + */ +function why(graph, packageName) { + const matches = Array.from(graph.nodes.values()).filter(n => n.name === packageName); + + return matches.map(node => ({ + node, + paths: findPaths(graph.edges, node.id) + })); +} + +module.exports = { why, findPaths, MAX_PATHS_PER_NODE }; diff --git a/src/features/analyze/collectors/cve.collector.js b/src/features/analyze/collectors/cve.collector.js index a39e374..babfd92 100644 --- a/src/features/analyze/collectors/cve.collector.js +++ b/src/features/analyze/collectors/cve.collector.js @@ -19,9 +19,11 @@ function resolveNearestFix(fixedVersions, installedVersion) { return pool[0].version; } -async function collectCVEData(projectPath, packageJson = null) { +async function collectCVEData(projectPath, packageJson = null, graph = null) { try { - const result = await vulnerabilityChecker.checkProject(projectPath, packageJson); + // With a lockfile graph, this checks every installed name@version in the + // tree, not just the direct dependencies. + const result = await vulnerabilityChecker.checkProject(projectPath, packageJson, { graph }); const rawVulns = result.vulnerabilities || []; const issues = rawVulns.length === 0 ? [] : collapsePerPackage(rawVulns); diff --git a/src/features/analyze/collectors/dependency.collector.js b/src/features/analyze/collectors/dependency.collector.js index 7bb14a0..e1f3988 100644 --- a/src/features/analyze/collectors/dependency.collector.js +++ b/src/features/analyze/collectors/dependency.collector.js @@ -1,63 +1,92 @@ // src/features/analyze/collectors/dependency.collector.js -const { exec } = require('child_process'); -const { promisify } = require('util'); const path = require('path'); const fs = require('fs'); +const semver = require('semver'); +const registryClient = require('../../../shared/services/registry-client'); const SemverValidator = require('../../../shared/utils/semver-validator'); const { analyzeUnusedDependencies } = require('./unused-deps.collector'); -const execAsync = promisify(exec); - -// A failed outdated check must not look like "everything is up to date". -function incompleteResult(reason) { - const result = []; - result.incomplete = true; - result.incompleteReason = reason; - return result; +// A range this can't meaningfully compare against a registry version: +// git/file/link/workspace protocols, tags ("latest"), and "*". +function isComparableRange(range) { + if (typeof range !== 'string' || range.trim() === '') return false; + if (/^(git|git\+|https?:|file:|link:|workspace:|npm:|github:)/i.test(range)) return false; + if (range === '*' || range === 'latest' || range === 'next') return false; + return semver.validRange(range) !== null; } async function collectOutdatedData(projectPath, packageJson = null) { + const packageJsonPath = path.join(projectPath, 'package.json'); try { if (!packageJson) { - const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) return []; - packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); + packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); } + const declared = { ...(packageJson.dependencies || {}), ...(packageJson.devDependencies || {}) }; - if (Object.keys(declared).length === 0) return []; + const names = Object.keys(declared).filter(name => isComparableRange(declared[name])); + if (names.length === 0) return []; + + // The npm registry client this project already ships, rather than + // npm-check-updates (6 MB, its own network stack, and run through npx) — + // "is there a newer version" only needs the published versions plus + // semver, and this client already has the 24h disk cache and retries. + const registryData = await registryClient.fetchBatch(names); + + if (registryData.size === 0) { + // Asked about packages and heard nothing back: a network/registry + // failure, not "everything is up to date". + const result = []; + result.incomplete = true; + result.incompleteReason = 'Could not reach the npm registry for any dependency'; + return result; + } + + const outdated = []; + for (const name of names) { + const data = registryData.get(name); + const latest = data?.version; + if (!latest || !semver.valid(latest)) continue; - // npm-check-updates compares package.json's declared ranges against the npm - // registry — it doesn't read package-lock.json at all. Gating on the - // lockfile's existence meant any yarn/pnpm project (no package-lock.json) - // or a freshly-cloned npm project (not yet `npm install`ed) silently got - // zero "outdated" findings, indistinguishable from being fully up to date. - const { stdout } = await execAsync('npx npm-check-updates --jsonUpgraded', { - cwd: projectPath, - encoding: 'utf8', - timeout: 30000, - maxBuffer: 10 * 1024 * 1024 - }); + const declaredRange = declared[name]; + const current = declaredRange.replace(/^[\^~>=<\s]+/, ''); + const currentCoerced = semver.coerce(current); + if (!currentCoerced) continue; - const lines = stdout.split('\n').filter(line => line.trim()); - let jsonLine = null; - for (const line of lines) { - if (line.startsWith('{') && line.endsWith('}')) { - try { JSON.parse(line); jsonLine = line; break; } catch (e) { continue; } - } + if (!semver.gt(latest, currentCoerced)) continue; + + // What the declared range would actually install today (what `npm + // update` would move to) — distinct from latest when the range pins a + // major. A cache entry from before `versions` was kept only knows + // latest, so it can only tell "latest is in range" from "it isn't". + const available = Array.isArray(data.versions) && data.versions.length > 0 ? data.versions : [latest, currentCoerced.version]; + outdated.push({ + name, + current, + latest, + wanted: semver.maxSatisfying(available, declaredRange) || current, + updateType: SemverValidator.getUpdateType(current, latest) + }); } - if (!jsonLine) return incompleteResult('npm-check-updates returned no result'); - const outdated = JSON.parse(jsonLine); + // Some packages resolved and some didn't (private/unpublished names, or + // partial registry failure) — report what we have, but don't let it read + // as a clean bill of health for the ones we never heard about. + if (registryData.size < names.length) { + outdated.incomplete = true; + outdated.incompleteReason = `Could not check ${names.length - registryData.size} of ${names.length} dependencies against the registry`; + } - return Object.entries(outdated).map(([name, latest]) => { - const current = packageJson.dependencies?.[name] || packageJson.devDependencies?.[name]; - const cleanCurrent = typeof current === 'string' ? current.replace(/^[\^~]/, '') : current; - return { name, current: cleanCurrent, latest, wanted: latest, updateType: SemverValidator.getUpdateType(cleanCurrent, latest) }; - }); + return outdated; } catch (error) { if (process.env.DEBUG) console.error('Outdated collection failed:', error.message); - return incompleteResult(`could not check for newer versions (${error.message.split('\n')[0]})`); + // An empty array here is indistinguishable from "everything is up to + // date" — mark it incomplete so the report says so instead. + const result = []; + result.incomplete = true; + result.incompleteReason = error.message; + return result; } } @@ -70,4 +99,4 @@ async function collectUnusedData(projectPath, packageJson = null) { } } -module.exports = { collectOutdatedData, collectUnusedData }; \ No newline at end of file +module.exports = { collectOutdatedData, collectUnusedData, isComparableRange }; diff --git a/src/features/analyze/collectors/index.js b/src/features/analyze/collectors/index.js index fd3653c..bb334d7 100644 --- a/src/features/analyze/collectors/index.js +++ b/src/features/analyze/collectors/index.js @@ -19,7 +19,7 @@ const { collectPredictiveData } = require('./predictive.collector'); * @property {string} label used in "