cve-lite-cli 1.23.1 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +56 -0
  2. package/dist/audit-log/events.js +3 -0
  3. package/dist/audit-log/handle.js +20 -0
  4. package/dist/audit-log/index.js +16 -0
  5. package/dist/audit-log/ndjson-writer.js +28 -0
  6. package/dist/cli/args.js +71 -3
  7. package/dist/cli/fix-overrides-hook.js +64 -0
  8. package/dist/cli/help.js +22 -0
  9. package/dist/cli/overrides.js +67 -0
  10. package/dist/index.js +270 -12
  11. package/dist/osv/cache.js +23 -3
  12. package/dist/output/formatters.js +23 -4
  13. package/dist/output/html-reporter.js +34 -4
  14. package/dist/output/override-findings-html.js +57 -0
  15. package/dist/output/override-findings-json.js +3 -0
  16. package/dist/output/override-findings-sarif.js +52 -0
  17. package/dist/output/override-findings-terminal.js +37 -0
  18. package/dist/output/printers.js +25 -8
  19. package/dist/output/sarif.js +77 -8
  20. package/dist/output/write-outputs.js +7 -3
  21. package/dist/overrides/api.js +79 -0
  22. package/dist/overrides/composite.js +23 -0
  23. package/dist/overrides/context-builder.js +150 -0
  24. package/dist/overrides/context.js +3 -0
  25. package/dist/overrides/detectors/index.js +23 -0
  26. package/dist/overrides/detectors/oa001-orphaned-target.js +36 -0
  27. package/dist/overrides/detectors/oa002-floating-tag.js +40 -0
  28. package/dist/overrides/detectors/oa003-wrong-section.js +48 -0
  29. package/dist/overrides/detectors/oa004-surpassed-pin.js +49 -0
  30. package/dist/overrides/detectors/oa005-nested-ineffective.js +128 -0
  31. package/dist/overrides/detectors/oa006-coupled-platform-binary.js +170 -0
  32. package/dist/overrides/detectors/oa007-frozen-latest.js +69 -0
  33. package/dist/overrides/detectors/oa008-materialized.js +75 -0
  34. package/dist/overrides/detectors/platform-binary.js +37 -0
  35. package/dist/overrides/fixer.js +199 -0
  36. package/dist/overrides/index.js +5 -0
  37. package/dist/overrides/parsing/installed-tree.js +164 -0
  38. package/dist/overrides/parsing/json-pointer.js +8 -0
  39. package/dist/overrides/parsing/node-modules.js +19 -0
  40. package/dist/overrides/parsing/package-json.js +139 -0
  41. package/dist/overrides/parsing/registry.js +66 -0
  42. package/dist/overrides/types.js +2 -0
  43. package/dist/parsers/yarn-lock.js +2 -2
  44. package/dist/remediation/fix-commands.js +110 -29
  45. package/dist/remediation/npm-registry.js +30 -0
  46. package/dist/remediation/npm-transitive-resolution.js +2 -2
  47. package/dist/remediation/transitive-chain-resolver.js +100 -0
  48. package/dist/scan/multi-folder-scan.js +26 -0
  49. package/dist/scanner.js +61 -5
  50. package/dist/types.js +13 -1
  51. package/dist/utils/baseline.js +16 -0
  52. package/dist/utils/create-pr.js +19 -4
  53. package/dist/utils/string.js +34 -0
  54. package/dist/utils/version.js +115 -0
  55. package/package.json +4 -2
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Heuristic: does this package name look like a platform-specific native binary?
3
+ *
4
+ * Used by OA006 to distinguish the genuinely-coupled case (override fights an
5
+ * exact-pinned parent that ships a native binary, like @esbuild/linux-x64)
6
+ * from the range-bumps-exact case (override on postcss against next's
7
+ * exact pin - risky but commonly intentional and usually works).
8
+ *
9
+ * Hits:
10
+ * @esbuild/linux-x64
11
+ * @next/swc-linux-x64-gnu
12
+ * @rollup/rollup-linux-x64-musl
13
+ * @swc/core-linux-x64-gnu
14
+ * @biomejs/cli-linux-x64
15
+ * @img/sharp-linux-x64
16
+ * @parcel/watcher-linux-x64-glibc
17
+ * @oxc-project/runtime-linux-x64-musl
18
+ * lightningcss-linux-x64-musl
19
+ * sharp-linux-x64
20
+ * esbuild-linux-x64
21
+ *
22
+ * Misses (correctly - these aren't platform binaries):
23
+ * postcss, react, next, esbuild (the JS parent itself), @scope/anything-not-platform
24
+ */
25
+ export function looksLikePlatformBinary(name) {
26
+ return PLATFORM_TOKEN_RE.test(name);
27
+ }
28
+ /**
29
+ * Matches a platform/OS token that appears as its own segment in the name:
30
+ * - at the start (e.g. "linux-x64")
31
+ * - after a slash (e.g. "@esbuild/linux-x64")
32
+ * - after a hyphen (e.g. "sharp-linux-x64", "swc-linux-x64-gnu")
33
+ *
34
+ * Followed by another segment boundary (slash, hyphen, underscore, end-of-string).
35
+ * Anchoring to segment boundaries avoids false positives like "android-base-utils".
36
+ */
37
+ const PLATFORM_TOKEN_RE = /(?:^|[-/])(linux|darwin|win32|windows|wasi|freebsd|openbsd|netbsd|sunos|android|cygwin)(?:[-/_]|$)/i;
@@ -0,0 +1,199 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { jsonPointer } from "./parsing/json-pointer.js";
4
+ export function applyFix(opts) {
5
+ const { projectPath, findings, auditLog, dryRun } = opts;
6
+ const applied = [];
7
+ const skipped = [];
8
+ const pkgPath = join(projectPath, "package.json");
9
+ const original = readFileSync(pkgPath, "utf8");
10
+ let state = JSON.parse(original);
11
+ for (const finding of findings) {
12
+ if (!finding.fix || finding.fix.type !== "rfc6902") {
13
+ skipped.push({
14
+ ruleId: finding.ruleId,
15
+ package: finding.package.name,
16
+ reason: "no fix patch attached",
17
+ });
18
+ continue;
19
+ }
20
+ const before = overrideKeySet(state);
21
+ let next = state;
22
+ try {
23
+ for (const op of finding.fix.patch) {
24
+ next = applyOp(next, op);
25
+ }
26
+ }
27
+ catch (err) {
28
+ skipped.push({
29
+ ruleId: finding.ruleId,
30
+ package: finding.package.name,
31
+ reason: err instanceof Error ? err.message : String(err),
32
+ });
33
+ continue;
34
+ }
35
+ // Chokepoint guard: override hygiene must never invent a new override key.
36
+ // The only sanctioned way to introduce a key is relocate, which writes a
37
+ // dependency floor, not an override. Reject and log anything that grows the
38
+ // override key set, and commit nothing for that finding.
39
+ const created = [...overrideKeySet(next)].filter((k) => !before.has(k));
40
+ if (created.length > 0) {
41
+ auditLog.emit({
42
+ ts: new Date().toISOString(),
43
+ type: "error",
44
+ schemaVersion: 1,
45
+ phase: "fix-guard",
46
+ message: `rejected fix for ${finding.ruleId} on ${finding.package.name}: ` +
47
+ `would create override key(s) ${created.join(", ")}`,
48
+ });
49
+ skipped.push({
50
+ ruleId: finding.ruleId,
51
+ package: finding.package.name,
52
+ reason: `fix-guard: would create override key(s) ${created.join(", ")}`,
53
+ });
54
+ continue;
55
+ }
56
+ state = next;
57
+ applied.push({
58
+ ruleId: finding.ruleId,
59
+ package: finding.package.name,
60
+ patches: finding.fix.patch.slice(),
61
+ });
62
+ auditLog.emit({
63
+ ts: new Date().toISOString(),
64
+ type: "oa.fix.applied",
65
+ schemaVersion: 1,
66
+ ruleId: finding.ruleId,
67
+ package: finding.package.name,
68
+ patches: finding.fix.patch.map(loggableOp),
69
+ });
70
+ }
71
+ if (!dryRun && applied.length > 0) {
72
+ const indent = detectIndent(original);
73
+ writeFileSync(pkgPath, JSON.stringify(state, null, indent) + "\n");
74
+ }
75
+ return {
76
+ appliedAt: new Date().toISOString(),
77
+ dryRun,
78
+ appliedPatches: applied,
79
+ skipped,
80
+ };
81
+ }
82
+ function detectIndent(raw) {
83
+ const m = raw.match(/^\{\n([ \t]+)/);
84
+ if (!m)
85
+ return 2;
86
+ return m[1].length;
87
+ }
88
+ function applyOp(doc, op) {
89
+ switch (op.op) {
90
+ case "remove":
91
+ return mutate(doc, op.path, () => undefined);
92
+ case "replace":
93
+ return mutate(doc, op.path, () => op.value);
94
+ case "move": {
95
+ const value = read(doc, op.from);
96
+ // The chokepoint guard rejects key-set growth, but a move into an already
97
+ // occupied destination (e.g. the same key in both overrides and
98
+ // pnpm.overrides) keeps the key count flat while clobbering an existing
99
+ // value. Refuse it so applyFix records a skip instead of silently
100
+ // overwriting.
101
+ if (read(doc, op.path) !== undefined) {
102
+ throw new Error(`move target ${op.path} already exists; refusing to overwrite it`);
103
+ }
104
+ doc = mutate(doc, op.from, () => undefined);
105
+ return mutate(doc, op.path, () => value);
106
+ }
107
+ case "relocate": {
108
+ // Retire the child override and carry its constraint as a parent dependency
109
+ // floor. This introduces a key under /dependencies (an upgrade), never a new
110
+ // override - the chokepoint guard in applyFix enforces that invariant.
111
+ doc = mutate(doc, op.fromChild, () => undefined);
112
+ return mutate(doc, jsonPointer(["dependencies", op.toParent]), () => op.floor);
113
+ }
114
+ }
115
+ }
116
+ /**
117
+ * Collect the set of keys under every override container. The chokepoint guard
118
+ * compares this before/after a fix: override hygiene may remove or repin existing
119
+ * overrides, but it must never invent a new one. relocate writes a dependency, not
120
+ * an override, so it does not grow this set.
121
+ */
122
+ function overrideKeySet(doc) {
123
+ const out = new Set();
124
+ const collect = (obj, prefix) => {
125
+ if (obj && typeof obj === "object") {
126
+ for (const k of Object.keys(obj))
127
+ out.add(prefix + k);
128
+ }
129
+ };
130
+ collect(doc.overrides, "overrides/");
131
+ const pnpm = doc.pnpm;
132
+ collect(pnpm?.overrides, "pnpm.overrides/");
133
+ collect(doc.resolutions, "resolutions/");
134
+ return out;
135
+ }
136
+ /** Loggable representation of a fix op (relocate has no single `path`). */
137
+ function loggableOp(op) {
138
+ if (op.op === "relocate") {
139
+ return { op: "relocate", path: op.fromChild, from: op.toParent, value: op.floor };
140
+ }
141
+ if (op.op === "move")
142
+ return { op: "move", path: op.path, from: op.from };
143
+ if (op.op === "remove")
144
+ return { op: "remove", path: op.path };
145
+ return { op: "replace", path: op.path, value: op.value };
146
+ }
147
+ function read(doc, pointer) {
148
+ const parts = splitPointer(pointer);
149
+ let cur = doc;
150
+ for (const p of parts)
151
+ cur = cur?.[p];
152
+ return cur;
153
+ }
154
+ function mutate(doc, pointer, fn) {
155
+ const parts = splitPointer(pointer);
156
+ if (parts.length === 0) {
157
+ throw new Error("cannot mutate root pointer");
158
+ }
159
+ const root = Array.isArray(doc) ? [...doc] : { ...doc };
160
+ let cur = root;
161
+ for (let i = 0; i < parts.length - 1; i++) {
162
+ const p = parts[i];
163
+ const next = cur[p];
164
+ if (next === undefined || next === null) {
165
+ cur[p] = {};
166
+ cur = cur[p];
167
+ }
168
+ else if (Array.isArray(next)) {
169
+ cur[p] = [...next];
170
+ cur = cur[p];
171
+ }
172
+ else if (typeof next === "object") {
173
+ cur[p] = { ...next };
174
+ cur = cur[p];
175
+ }
176
+ else {
177
+ throw new Error(`cannot descend into non-object at ${parts.slice(0, i + 1).join("/")}`);
178
+ }
179
+ }
180
+ const last = parts[parts.length - 1];
181
+ const newValue = fn(cur[last]);
182
+ if (newValue === undefined) {
183
+ delete cur[last];
184
+ }
185
+ else {
186
+ cur[last] = newValue;
187
+ }
188
+ return root;
189
+ }
190
+ function splitPointer(pointer) {
191
+ if (pointer === "")
192
+ return [];
193
+ if (!pointer.startsWith("/"))
194
+ throw new Error(`bad RFC6902 pointer: ${pointer}`);
195
+ return pointer
196
+ .slice(1)
197
+ .split("/")
198
+ .map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
199
+ }
@@ -0,0 +1,5 @@
1
+ export { buildOverrideContext } from "./context-builder.js";
2
+ export { ALL_DETECTORS, VERIFY_DETECTORS } from "./detectors/index.js";
3
+ export { audit, verify } from "./api.js";
4
+ export { applyFix } from "./fixer.js";
5
+ export { applyComposite } from "./composite.js";
@@ -0,0 +1,164 @@
1
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * Walk node_modules trees recursively to gather two indices:
5
+ * 1. installedCopies - name -> all copies of that name anywhere in the tree
6
+ * 2. parentDeclarations - name -> parents that declare it as a (opt|peer)Dependency
7
+ *
8
+ * Both are populated in one pass to amortise the directory walk. The walk is
9
+ * shallow-ish: it follows `node_modules/<a>/node_modules/<b>/node_modules/...`
10
+ * but does not chase symlinks (avoids workspace-protocol cycles).
11
+ *
12
+ * Returns empty maps when `node_modules` does not exist - callers should fall
13
+ * back to lockfile-only signals (and surface a skippedDetectors note).
14
+ */
15
+ export function walkInstalledTree(projectPath) {
16
+ const installedCopies = new Map();
17
+ const parentDeclarations = new Map();
18
+ const root = join(projectPath, 'node_modules');
19
+ if (!existsSync(root))
20
+ return { installedCopies, parentDeclarations };
21
+ // Dedupe by canonical path so a package reachable both as a top-level symlink
22
+ // and via the .pnpm store (or through symlink cycles) is recorded only once.
23
+ const visited = new Set();
24
+ walk(root, installedCopies, parentDeclarations, visited);
25
+ return { installedCopies, parentDeclarations };
26
+ }
27
+ function walk(nmDir, copies, parents, visited) {
28
+ let entries;
29
+ try {
30
+ entries = readdirSync(nmDir);
31
+ }
32
+ catch {
33
+ return;
34
+ }
35
+ for (const entry of entries) {
36
+ // pnpm keeps every real package copy in its virtual store; descend into it so
37
+ // transitive (non-hoisted) packages are not invisible. Must run before the
38
+ // dot-skip below since the store dir is named `.pnpm`.
39
+ if (entry === '.pnpm') {
40
+ walkPnpmStore(join(nmDir, entry), copies, parents, visited);
41
+ continue;
42
+ }
43
+ if (entry.startsWith('.'))
44
+ continue; // skip .bin, .package-lock.json, .cache, etc.
45
+ const entryPath = join(nmDir, entry);
46
+ // Scoped packages: recurse into the scope directory which contains the actual packages.
47
+ if (entry.startsWith('@')) {
48
+ let scopeEntries;
49
+ try {
50
+ scopeEntries = readdirSync(entryPath);
51
+ }
52
+ catch {
53
+ continue;
54
+ }
55
+ for (const scopedEntry of scopeEntries) {
56
+ const pkgPath = join(entryPath, scopedEntry);
57
+ const fullName = `${entry}/${scopedEntry}`;
58
+ processPackage(pkgPath, fullName, copies, parents, visited);
59
+ }
60
+ continue;
61
+ }
62
+ processPackage(entryPath, entry, copies, parents, visited);
63
+ }
64
+ }
65
+ /**
66
+ * pnpm stores every real package copy at
67
+ * `.pnpm/<name>@<version>/node_modules/<name>` (scoped names encode `/` as `+`,
68
+ * e.g. `@scope+pkg@1.0.0`). The top-level `node_modules` only symlinks direct
69
+ * deps, so transitive override targets never appear in the nested-node_modules
70
+ * walk. Descend into each store entry and process the real package directory;
71
+ * sibling deps inside the entry are symlinks back into the store, so they are
72
+ * skipped here (and deduped by realpath in processPackage regardless).
73
+ */
74
+ function walkPnpmStore(pnpmDir, copies, parents, visited) {
75
+ let keys;
76
+ try {
77
+ keys = readdirSync(pnpmDir);
78
+ }
79
+ catch {
80
+ return;
81
+ }
82
+ for (const key of keys) {
83
+ if (key.startsWith('.'))
84
+ continue; // .modules.yaml, lock, node_modules markers
85
+ const innerNm = join(pnpmDir, key, 'node_modules');
86
+ // The package's own copy lives under its real name; sibling deps are symlinks.
87
+ walk(innerNm, copies, parents, visited);
88
+ }
89
+ }
90
+ function processPackage(pkgPath, pkgName, copies, parents, visited) {
91
+ let stats;
92
+ try {
93
+ stats = statSync(pkgPath);
94
+ }
95
+ catch {
96
+ return;
97
+ }
98
+ if (!stats.isDirectory())
99
+ return;
100
+ // Dedupe by canonical path: a package reachable via a top-level symlink and via
101
+ // the .pnpm store resolves to the same real directory and must be counted once.
102
+ let realPath;
103
+ try {
104
+ realPath = realpathSync(pkgPath);
105
+ }
106
+ catch {
107
+ realPath = pkgPath;
108
+ }
109
+ if (visited.has(realPath))
110
+ return;
111
+ visited.add(realPath);
112
+ const manifestPath = join(pkgPath, 'package.json');
113
+ if (!existsSync(manifestPath))
114
+ return;
115
+ let manifest;
116
+ try {
117
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
118
+ }
119
+ catch {
120
+ return;
121
+ }
122
+ const version = manifest.version;
123
+ if (version) {
124
+ const list = copies.get(pkgName) ?? [];
125
+ list.push({ name: pkgName, path: pkgPath, version });
126
+ copies.set(pkgName, list);
127
+ }
128
+ // Record this package as a parent for each of its declared deps.
129
+ recordDeclarations(manifest, pkgName, manifest.version ?? '', parents);
130
+ // Recurse into this package's own node_modules (nested deps).
131
+ const nested = join(pkgPath, 'node_modules');
132
+ if (existsSync(nested))
133
+ walk(nested, copies, parents, visited);
134
+ }
135
+ function recordDeclarations(manifest, parentName, parentVersion, parents) {
136
+ const sections = [
137
+ { deps: manifest.dependencies, declaredIn: 'dependencies' },
138
+ { deps: manifest.optionalDependencies, declaredIn: 'optionalDependencies' },
139
+ { deps: manifest.peerDependencies, declaredIn: 'peerDependencies' },
140
+ ];
141
+ for (const { deps, declaredIn } of sections) {
142
+ if (!deps)
143
+ continue;
144
+ for (const [depName, declaredValue] of Object.entries(deps)) {
145
+ const list = parents.get(depName) ?? [];
146
+ list.push({
147
+ parentName,
148
+ parentVersion,
149
+ declaredIn,
150
+ declaredValue,
151
+ exactVersion: isExactPin(declaredValue),
152
+ });
153
+ parents.set(depName, list);
154
+ }
155
+ }
156
+ }
157
+ /**
158
+ * An "exact" pin is a bare semver version with no range operators or qualifiers
159
+ * (e.g. "0.25.12" not "^0.25.0" or ">=0.25.0"). Matches what npm/pnpm treat as
160
+ * a single-version pin for resolution purposes.
161
+ */
162
+ function isExactPin(value) {
163
+ return /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/.test(value.trim());
164
+ }
@@ -0,0 +1,8 @@
1
+ /** Encode one path segment per RFC 6901 (~0 for ~, ~1 for /). */
2
+ export function escapeSegment(s) {
3
+ return s.replace(/~/g, '~0').replace(/\//g, '~1');
4
+ }
5
+ /** Build an RFC 6901 JSON Pointer from a path array. */
6
+ export function jsonPointer(path) {
7
+ return '/' + path.map(escapeSegment).join('/');
8
+ }
@@ -0,0 +1,19 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /** Return the installed version of `pkgName` under `projectPath`, or null. */
4
+ export function readInstalledVersion(projectPath, pkgName) {
5
+ const m = readInstalledManifest(projectPath, pkgName);
6
+ return m?.version ?? null;
7
+ }
8
+ /** Return the parsed `node_modules/<pkgName>/package.json`, or null. */
9
+ export function readInstalledManifest(projectPath, pkgName) {
10
+ const path = join(projectPath, 'node_modules', pkgName, 'package.json');
11
+ if (!existsSync(path))
12
+ return null;
13
+ try {
14
+ return JSON.parse(readFileSync(path, 'utf-8'));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
@@ -0,0 +1,139 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export class MalformedPackageJsonError extends Error {
4
+ path;
5
+ cause;
6
+ constructor(path, cause) {
7
+ super(`Failed to parse package.json at ${path}: ${cause?.message ?? String(cause)}`);
8
+ this.path = path;
9
+ this.cause = cause;
10
+ this.name = 'MalformedPackageJsonError';
11
+ }
12
+ }
13
+ export function readPackageJson(projectPath) {
14
+ const path = join(projectPath, 'package.json');
15
+ let raw;
16
+ try {
17
+ raw = readFileSync(path, 'utf-8');
18
+ }
19
+ catch (err) {
20
+ throw new MalformedPackageJsonError(path, err);
21
+ }
22
+ try {
23
+ const parsed = JSON.parse(raw);
24
+ return { parsed, raw };
25
+ }
26
+ catch (err) {
27
+ throw new MalformedPackageJsonError(path, err);
28
+ }
29
+ }
30
+ /**
31
+ * Strip pnpm's optional `@<specifier>` suffix from an override key segment.
32
+ * Handles both `pkg@>=1.0.0` and `@scope/pkg@>=1.0.0`.
33
+ *
34
+ * NOTE: this operates on a single segment and does NOT split pnpm selective
35
+ * `parent>child` keys. Splitting on `>` is handled by `parseOverrideKey`,
36
+ * which feeds each side through `bareName` separately.
37
+ */
38
+ export function bareName(overrideKey) {
39
+ if (overrideKey.startsWith('@')) {
40
+ // Scoped: keep the leading @, look for the SECOND @ as specifier delimiter.
41
+ const second = overrideKey.indexOf('@', 1);
42
+ return second === -1 ? overrideKey : overrideKey.slice(0, second);
43
+ }
44
+ const at = overrideKey.indexOf('@');
45
+ return at === -1 ? overrideKey : overrideKey.slice(0, at);
46
+ }
47
+ /**
48
+ * Index of the `@` that introduces a version specifier on a single selector,
49
+ * or -1 if there is none. For scoped names the leading `@` (index 0) is the
50
+ * scope, not a specifier, so we look past it.
51
+ */
52
+ function specifierAt(selector) {
53
+ if (selector.startsWith('@')) {
54
+ return selector.indexOf('@', 1);
55
+ }
56
+ return selector.indexOf('@');
57
+ }
58
+ /**
59
+ * Resolve an override key into its real target package name and (for pnpm
60
+ * selective `parent>child` keys) the parent scope.
61
+ *
62
+ * - Plain key (`postcss`, `@babel/runtime@<7.26.10`, `debug@>=4.0.0 <4.3.1`):
63
+ * no SELECTIVE `>`, so `packageName = bareName(key)` and `parentScope`
64
+ * stays undefined. Unchanged from the historical behavior. Note that a `>`
65
+ * inside a semver range (`@>=4.0.0`) is NOT a selective separator: it always
66
+ * follows the specifier `@`, so we only treat a `>` that appears BEFORE the
67
+ * specifier `@` as the pnpm `parent>child` separator.
68
+ * - pnpm selective key (`parent>child`, `parent>@scope/child`): split on that
69
+ * FIRST selective `>`; the child (after `>`, with any `@spec` stripped) is
70
+ * the real target, the parent (also bareName'd) is the scope.
71
+ */
72
+ export function parseOverrideKey(overrideKey) {
73
+ const gt = overrideKey.indexOf('>');
74
+ const spec = specifierAt(overrideKey);
75
+ // A `>` is the selective separator only if it precedes any version
76
+ // specifier `@` (otherwise it belongs to a semver comparator like `@>=`).
77
+ const isSelective = gt !== -1 && (spec === -1 || gt < spec);
78
+ if (!isSelective) {
79
+ return { packageName: bareName(overrideKey) };
80
+ }
81
+ const parent = overrideKey.slice(0, gt);
82
+ const childRaw = overrideKey.slice(gt + 1);
83
+ return {
84
+ packageName: bareName(childRaw),
85
+ parentScope: bareName(parent),
86
+ };
87
+ }
88
+ /**
89
+ * Extract all override entries from `overrides` (npm/bun), `pnpm.overrides`,
90
+ * and `resolutions` (yarn), preserving nested-object values without flattening
91
+ * them. Each entry records its container so detectors can reason about
92
+ * misplacement.
93
+ */
94
+ export function extractOverrideEntries(pkgJson) {
95
+ const out = [];
96
+ const npmOverrides = pkgJson.overrides;
97
+ if (npmOverrides && typeof npmOverrides === 'object') {
98
+ for (const [key, value] of Object.entries(npmOverrides)) {
99
+ const { packageName, parentScope } = parseOverrideKey(key);
100
+ out.push({
101
+ key,
102
+ packageName,
103
+ ...(parentScope !== undefined ? { parentScope } : {}),
104
+ value,
105
+ path: ['overrides', key],
106
+ container: 'overrides',
107
+ });
108
+ }
109
+ }
110
+ const pnpmSection = pkgJson.pnpm;
111
+ if (pnpmSection?.overrides && typeof pnpmSection.overrides === 'object') {
112
+ for (const [key, value] of Object.entries(pnpmSection.overrides)) {
113
+ const { packageName, parentScope } = parseOverrideKey(key);
114
+ out.push({
115
+ key,
116
+ packageName,
117
+ ...(parentScope !== undefined ? { parentScope } : {}),
118
+ value,
119
+ path: ['pnpm', 'overrides', key],
120
+ container: 'pnpm.overrides',
121
+ });
122
+ }
123
+ }
124
+ const yarnResolutions = pkgJson.resolutions;
125
+ if (yarnResolutions && typeof yarnResolutions === 'object') {
126
+ for (const [key, value] of Object.entries(yarnResolutions)) {
127
+ const { packageName, parentScope } = parseOverrideKey(key);
128
+ out.push({
129
+ key,
130
+ packageName,
131
+ ...(parentScope !== undefined ? { parentScope } : {}),
132
+ value,
133
+ path: ['resolutions', key],
134
+ container: 'resolutions',
135
+ });
136
+ }
137
+ }
138
+ return out;
139
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Fetch the `dist-tags` map for `pkgName` from the npm registry.
3
+ *
4
+ * Returns null on any failure (network error, non-200, parse error, timeout).
5
+ * The caller surfaces a `skippedDetectors` note when this returns null for a
6
+ * rule that depends on registry data.
7
+ *
8
+ * Per scan, callers should batch-fetch all needed packages in parallel and
9
+ * cache the result on `Context.registryDistTags`. This function is single-shot;
10
+ * caching/batching is the scanner's responsibility.
11
+ */
12
+ export async function fetchDistTags(pkgName, opts = {}) {
13
+ const baseUrl = opts.baseUrl ?? 'https://registry.npmjs.org';
14
+ const timeoutMs = opts.timeoutMs ?? 5000;
15
+ const fetchImpl = opts.fetchImpl ?? fetch;
16
+ const url = `${baseUrl}/${encodeRegistryPath(pkgName)}`;
17
+ const controller = new AbortController();
18
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
19
+ try {
20
+ const res = await fetchImpl(url, {
21
+ signal: controller.signal,
22
+ headers: {
23
+ Accept: 'application/vnd.npm.install-v1+json',
24
+ 'User-Agent': 'override-audit-cli',
25
+ },
26
+ });
27
+ if (!res.ok)
28
+ return null;
29
+ const body = await res.json();
30
+ return body['dist-tags'] ?? null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
39
+ /**
40
+ * Fetch dist-tags for many packages concurrently. Failures collapse to null
41
+ * (per-package), so a single 404 doesn't tank the whole batch.
42
+ */
43
+ export async function fetchDistTagsBatch(pkgNames, opts = {}) {
44
+ const out = new Map();
45
+ const unique = Array.from(new Set(pkgNames));
46
+ await Promise.all(unique.map(async (name) => {
47
+ const tags = await fetchDistTags(name, opts);
48
+ if (tags)
49
+ out.set(name, tags);
50
+ }));
51
+ return out;
52
+ }
53
+ /**
54
+ * Encode a package name for the registry URL.
55
+ * Scoped names like `@scope/pkg` need the slash kept literal — the registry
56
+ * doesn't accept `%2F` for the scope separator.
57
+ */
58
+ function encodeRegistryPath(pkgName) {
59
+ if (pkgName.startsWith('@')) {
60
+ const slash = pkgName.indexOf('/');
61
+ if (slash === -1)
62
+ return encodeURIComponent(pkgName);
63
+ return encodeURIComponent(pkgName.slice(0, slash)) + '/' + encodeURIComponent(pkgName.slice(slash + 1));
64
+ }
65
+ return encodeURIComponent(pkgName);
66
+ }
@@ -0,0 +1,2 @@
1
+ // Override-audit rule identifiers. Spec: docs/merge/2026-05-28-cve-lite-merge-design.md
2
+ export {};
@@ -207,8 +207,8 @@ function loadFromYarnBerryLock(content, filePath) {
207
207
  continue;
208
208
  const depKeys = new Set();
209
209
  for (const [depName, depRef] of Object.entries(parseBerryDependencies(block))) {
210
- const childSelector = depRef.startsWith("npm:") ? `${depName}@${depRef}` : `${depName}@${depRef}`;
211
- const childKey = selectorToKey.get(childSelector);
210
+ const childKey = selectorToKey.get(`${depName}@${depRef}`) ??
211
+ selectorToKey.get(`${depName}@npm:${depRef}`);
212
212
  if (childKey)
213
213
  depKeys.add(childKey);
214
214
  }