cve-lite-cli 1.33.0 → 1.35.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 (53) hide show
  1. package/README.md +6 -3
  2. package/dist/advisory/local-db.js +31 -2
  3. package/dist/advisory/osv-advisory-source.js +3 -0
  4. package/dist/cli/advisories-init.js +13 -0
  5. package/dist/cli/advisories-sync.js +30 -0
  6. package/dist/cli/args.js +41 -2
  7. package/dist/cli/config-command.js +15 -0
  8. package/dist/cli/config.js +29 -0
  9. package/dist/cli/help.js +7 -5
  10. package/dist/cli/overrides.js +10 -1
  11. package/dist/cli/validate.js +6 -2
  12. package/dist/constants.js +52 -0
  13. package/dist/index.js +25 -719
  14. package/dist/output/cyclonedx.js +28 -24
  15. package/dist/output/formatters.js +13 -0
  16. package/dist/output/html-reporter.js +81 -40
  17. package/dist/output/multi-folder-html-reporter.js +16 -10
  18. package/dist/output/multi-folder-printer.js +1 -1
  19. package/dist/output/override-findings-sarif.js +1 -0
  20. package/dist/output/printers.js +436 -271
  21. package/dist/output/sarif.js +17 -1
  22. package/dist/output/sbom-dependency-edges.js +86 -0
  23. package/dist/output/sbom-file.js +27 -0
  24. package/dist/output/spdx.js +293 -0
  25. package/dist/output/write-outputs.js +18 -3
  26. package/dist/overrides/admitted-scan.js +158 -0
  27. package/dist/overrides/api.js +16 -0
  28. package/dist/overrides/context-builder.js +4 -0
  29. package/dist/overrides/context.js +8 -1
  30. package/dist/overrides/detectors/index.js +2 -0
  31. package/dist/overrides/detectors/oa010-vulnerable-floor.js +123 -0
  32. package/dist/overrides/parsing/registry.js +53 -0
  33. package/dist/parsers/bun-lock-graph.js +182 -0
  34. package/dist/parsers/bun-lock.js +93 -132
  35. package/dist/parsers/index.js +75 -149
  36. package/dist/parsers/multi-package.js +5 -6
  37. package/dist/parsers/package-lock.js +11 -1
  38. package/dist/parsers/pnpm-lock-graph.js +94 -0
  39. package/dist/parsers/pnpm-lock.js +5 -5
  40. package/dist/parsers/utils.js +3 -0
  41. package/dist/parsers/yarn-lock-graph.js +148 -0
  42. package/dist/parsers/yarn-lock.js +3 -3
  43. package/dist/remediation/fix-commands.js +48 -7
  44. package/dist/remediation/npm-registry.js +8 -2
  45. package/dist/scan/completeness.js +1 -0
  46. package/dist/scan/single-scan.js +643 -0
  47. package/dist/scanner.js +62 -7
  48. package/dist/types.js +1 -1
  49. package/dist/utils/file.js +11 -14
  50. package/dist/utils/purl.js +10 -0
  51. package/dist/utils/sbom-format.js +12 -0
  52. package/dist/utils/version.js +84 -10
  53. package/package.json +2 -2
@@ -1,164 +1,90 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { LOCKFILE_NAMES, LOCKFILE_PRIORITY_ROOT } from "../constants.js";
3
4
  import { findFiles, findNearestPackageJson, chooseBestLockfile, safeReadText, relativeOrName } from "../utils/file.js";
4
5
  import { loadFromBunLock } from "./bun-lock.js";
5
6
  import { loadFromPackageJson } from "./package-json.js";
6
7
  import { loadFromPackageLock } from "./package-lock.js";
7
8
  import { loadFromPnpmLock } from "./pnpm-lock.js";
8
9
  import { loadFromYarnLock } from "./yarn-lock.js";
9
- export function loadPackages(projectRoot, prodOnly, maxDepth) {
10
- const rootBunLock = path.join(projectRoot, "bun.lock");
11
- const rootShrinkwrap = path.join(projectRoot, "npm-shrinkwrap.json");
12
- const rootPackageLock = path.join(projectRoot, "package-lock.json");
13
- const rootPnpmLock = path.join(projectRoot, "pnpm-lock.yaml");
14
- const rootYarnLock = path.join(projectRoot, "yarn.lock");
15
- if (fs.existsSync(rootBunLock)) {
16
- return {
17
- mode: "resolved-lockfile",
18
- source: "bun-lock",
19
- filePath: rootBunLock,
20
- packages: loadFromBunLock(rootBunLock, prodOnly),
21
- notes: [
22
- "Scanned resolved dependency versions from bun.lock.",
23
- "Dependency paths are derived from bun.lock package relationships."
24
- ],
25
- warnings: [],
26
- skippedDependencies: []
27
- };
28
- }
29
- if (fs.existsSync(rootShrinkwrap)) {
30
- return {
31
- mode: "resolved-lockfile",
32
- source: "npm-shrinkwrap",
33
- filePath: rootShrinkwrap,
34
- packages: loadFromPackageLock(rootShrinkwrap, prodOnly),
35
- notes: [
36
- "Scanned resolved dependency versions from npm-shrinkwrap.json.",
37
- "Dependency paths are derived from lockfile package locations."
38
- ],
39
- warnings: [],
40
- skippedDependencies: []
41
- };
42
- }
43
- if (fs.existsSync(rootPackageLock)) {
44
- return {
45
- mode: "resolved-lockfile",
46
- source: "package-lock",
47
- filePath: rootPackageLock,
48
- packages: loadFromPackageLock(rootPackageLock, prodOnly),
49
- notes: [
50
- "Scanned resolved dependency versions from package-lock.json.",
51
- "Dependency paths are derived from lockfile package locations."
52
- ],
53
- warnings: [],
54
- skippedDependencies: []
55
- };
56
- }
57
- if (fs.existsSync(rootPnpmLock)) {
58
- return {
59
- mode: "resolved-lockfile",
60
- source: "pnpm-lock",
61
- filePath: rootPnpmLock,
62
- packages: loadFromPnpmLock(rootPnpmLock, prodOnly),
63
- notes: [
64
- "Scanned resolved dependency versions from pnpm-lock.yaml.",
65
- "Dependency paths are approximated from importer relationships and package snapshots."
66
- ],
67
- warnings: [],
68
- skippedDependencies: []
69
- };
10
+ const NESTED_LOCKFILE_NOTE = "No supported lockfile was found at the repo root, so a nested lockfile was used instead.";
11
+ const PATHS_FROM_LOCKFILE_LOCATIONS = "Dependency paths are derived from lockfile package locations.";
12
+ /**
13
+ * How to read each supported lockfile. Keyed by filename so every entry in
14
+ * LOCKFILE_NAMES is required to have one, which the compiler checks.
15
+ * Precedence lives in the LOCKFILE_PRIORITY_* lists, never here.
16
+ */
17
+ const LOCKFILE_HANDLERS = {
18
+ "bun.lock": {
19
+ source: "bun-lock",
20
+ load: loadFromBunLock,
21
+ pathNote: "Dependency paths are derived from bun.lock package relationships.",
22
+ },
23
+ "npm-shrinkwrap.json": {
24
+ source: "npm-shrinkwrap",
25
+ load: loadFromPackageLock,
26
+ pathNote: PATHS_FROM_LOCKFILE_LOCATIONS,
27
+ },
28
+ "package-lock.json": {
29
+ source: "package-lock",
30
+ load: loadFromPackageLock,
31
+ pathNote: PATHS_FROM_LOCKFILE_LOCATIONS,
32
+ },
33
+ "pnpm-lock.yaml": {
34
+ source: "pnpm-lock",
35
+ load: loadFromPnpmLock,
36
+ pathNote: "Dependency paths are approximated from importer relationships and package snapshots.",
37
+ },
38
+ "yarn.lock": {
39
+ // yarn.lock records no dev/prod distinction, so prodOnly does not apply.
40
+ source: "yarn-lock",
41
+ load: loadFromYarnLock,
42
+ pathNote: "Dependency paths are derived from yarn.lock package relationships.",
43
+ },
44
+ };
45
+ /** Narrows a discovered path to a supported lockfile name, or null. */
46
+ function toLockfileName(filePath) {
47
+ const name = path.basename(filePath);
48
+ return LOCKFILE_NAMES.find(candidate => candidate === name) ?? null;
49
+ }
50
+ /** First lockfile present at the repo root, in precedence order. */
51
+ function findRootLockfile(projectRoot) {
52
+ for (const name of LOCKFILE_PRIORITY_ROOT) {
53
+ const filePath = path.join(projectRoot, name);
54
+ if (fs.existsSync(filePath)) {
55
+ return { filePath, name };
56
+ }
70
57
  }
71
- if (fs.existsSync(rootYarnLock)) {
72
- return {
73
- mode: "resolved-lockfile",
74
- source: "yarn-lock",
75
- filePath: rootYarnLock,
76
- packages: loadFromYarnLock(rootYarnLock),
77
- notes: [
78
- "Scanned resolved dependency versions from yarn.lock.",
79
- "Dependency paths are derived from yarn.lock package relationships."
80
- ],
81
- warnings: [],
82
- skippedDependencies: []
83
- };
58
+ return null;
59
+ }
60
+ function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
61
+ const handler = LOCKFILE_HANDLERS[name];
62
+ return {
63
+ mode: "resolved-lockfile",
64
+ source: handler.source,
65
+ filePath,
66
+ packages: handler.load(filePath, prodOnly),
67
+ notes: [
68
+ `Scanned resolved dependency versions from ${label}.`,
69
+ handler.pathNote,
70
+ ...extraNotes,
71
+ ],
72
+ warnings: [],
73
+ skippedDependencies: [],
74
+ };
75
+ }
76
+ export function loadPackages(projectRoot, prodOnly, maxDepth) {
77
+ const rootLockfile = findRootLockfile(projectRoot);
78
+ if (rootLockfile !== null) {
79
+ return buildLockfileScan(rootLockfile.filePath, rootLockfile.name, prodOnly, rootLockfile.name, []);
84
80
  }
85
- const discoveredLockfiles = findFiles(projectRoot, ["bun.lock", "npm-shrinkwrap.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"], maxDepth);
81
+ const discoveredLockfiles = findFiles(projectRoot, [...LOCKFILE_NAMES], maxDepth);
86
82
  if (discoveredLockfiles.length > 0) {
87
83
  const selected = chooseBestLockfile(discoveredLockfiles);
88
- const selectedName = path.basename(selected);
89
- if (selectedName === "bun.lock") {
90
- return {
91
- mode: "resolved-lockfile",
92
- source: "bun-lock",
93
- filePath: selected,
94
- packages: loadFromBunLock(selected, prodOnly),
95
- notes: [
96
- `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
97
- "Dependency paths are derived from bun.lock package relationships.",
98
- "No supported lockfile was found at the repo root — a nested lockfile was used instead."
99
- ],
100
- warnings: [],
101
- skippedDependencies: []
102
- };
103
- }
104
- if (selectedName === "npm-shrinkwrap.json") {
105
- return {
106
- mode: "resolved-lockfile",
107
- source: "npm-shrinkwrap",
108
- filePath: selected,
109
- packages: loadFromPackageLock(selected, prodOnly),
110
- notes: [
111
- `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
112
- "Dependency paths are derived from lockfile package locations.",
113
- "No supported lockfile was found at the repo root — a nested lockfile was used instead."
114
- ],
115
- warnings: [],
116
- skippedDependencies: []
117
- };
118
- }
119
- if (selectedName === "package-lock.json") {
120
- return {
121
- mode: "resolved-lockfile",
122
- source: "package-lock",
123
- filePath: selected,
124
- packages: loadFromPackageLock(selected, prodOnly),
125
- notes: [
126
- `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
127
- "Dependency paths are derived from lockfile package locations.",
128
- "No supported lockfile was found at the repo root — a nested lockfile was used instead."
129
- ],
130
- warnings: [],
131
- skippedDependencies: []
132
- };
133
- }
134
- if (selectedName === "pnpm-lock.yaml") {
135
- return {
136
- mode: "resolved-lockfile",
137
- source: "pnpm-lock",
138
- filePath: selected,
139
- packages: loadFromPnpmLock(selected, prodOnly),
140
- notes: [
141
- `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
142
- "Dependency paths are approximated from importer relationships and package snapshots.",
143
- "No supported lockfile was found at the repo root — a nested lockfile was used instead."
144
- ],
145
- warnings: [],
146
- skippedDependencies: []
147
- };
84
+ const selectedName = toLockfileName(selected);
85
+ if (selectedName !== null) {
86
+ return buildLockfileScan(selected, selectedName, prodOnly, relativeOrName(projectRoot, selected), [NESTED_LOCKFILE_NOTE]);
148
87
  }
149
- return {
150
- mode: "resolved-lockfile",
151
- source: "yarn-lock",
152
- filePath: selected,
153
- packages: loadFromYarnLock(selected),
154
- notes: [
155
- `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
156
- "Dependency paths are derived from yarn.lock package relationships.",
157
- "No supported lockfile was found at the repo root — a nested lockfile was used instead."
158
- ],
159
- warnings: [],
160
- skippedDependencies: []
161
- };
162
88
  }
163
89
  const packageJsonPath = findNearestPackageJson(projectRoot, maxDepth);
164
90
  if (packageJsonPath) {
@@ -200,7 +126,7 @@ export function loadPackages(projectRoot, prodOnly, maxDepth) {
200
126
  export function buildNoPackagesMessage(projectRoot) {
201
127
  return [
202
128
  "No scannable packages were found.",
203
- "Supported inputs: bun.lock, npm-shrinkwrap.json, package-lock.json, pnpm-lock.yaml, yarn.lock, or package.json with exact pinned versions.",
129
+ `Supported inputs: ${[...LOCKFILE_NAMES].sort().join(", ")}, or package.json with exact pinned versions.`,
204
130
  `Searched under: ${projectRoot}`
205
131
  ].join(" ");
206
132
  }
@@ -1,8 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { EXCLUDED_DIRS } from "../constants.js";
3
+ import { EXCLUDED_DIRS, LOCKFILE_NAMES, LOCKFILE_PRIORITY_NESTED } from "../constants.js";
4
4
  import { loadPackages } from "./index.js";
5
- const LOCKFILE_NAMES = ["bun.lock", "npm-shrinkwrap.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"];
6
5
  export function hasRootLockfile(projectRoot) {
7
6
  return LOCKFILE_NAMES.some(name => fs.existsSync(path.join(projectRoot, name)));
8
7
  }
@@ -18,10 +17,10 @@ export function findNestedLockfiles(projectRoot, maxDepth) {
18
17
  catch {
19
18
  return;
20
19
  }
21
- const lockfile = entries.find(e => e.isFile() && LOCKFILE_NAMES.includes(e.name));
22
- if (lockfile) {
23
- results.push(path.join(dir, lockfile.name));
24
- return; // stop recursing — this lockfile covers its subtree
20
+ const lockfileName = LOCKFILE_PRIORITY_NESTED.find(name => entries.some(entry => entry.isFile() && entry.name === name));
21
+ if (lockfileName) {
22
+ results.push(path.join(dir, lockfileName));
23
+ return; // stop recursing, this lockfile covers its subtree
25
24
  }
26
25
  for (const entry of entries) {
27
26
  if (!entry.isDirectory())
@@ -24,6 +24,15 @@ export function buildNpmWorkspaceMap(filePath) {
24
24
  }
25
25
  return map;
26
26
  }
27
+ /**
28
+ * npm records a package's declared license in package-lock.json v2/v3, so we
29
+ * get it without touching the registry. Very old manifests used the object
30
+ * form `{ type, url }`; only the modern SPDX expression string is usable as-is,
31
+ * so anything else is treated as absent rather than stringified into nonsense.
32
+ */
33
+ function readLockfileLicense(value) {
34
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
35
+ }
27
36
  export function loadFromPackageLock(filePath, prodOnly) {
28
37
  const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
29
38
  const map = new Map();
@@ -45,7 +54,8 @@ export function loadFromPackageLock(filePath, prodOnly) {
45
54
  const graphPaths = nodeIds.flatMap(id => graph.pathsFor(id));
46
55
  const paths = graphPaths.length > 0 ? graphPaths : [normalizeNodeModulesPath(pkgPath)];
47
56
  const resolvedUrl = meta?.resolved;
48
- upsertPackage(map, { name, version, ecosystem: "npm", dev, paths, resolvedUrl });
57
+ const license = readLockfileLicense(meta?.license);
58
+ upsertPackage(map, { name, version, ecosystem: "npm", dev, paths, resolvedUrl, license });
49
59
  }
50
60
  }
51
61
  if (map.size === 0 && raw.dependencies && typeof raw.dependencies === "object") {
@@ -0,0 +1,94 @@
1
+ import { readAndParsePnpmLock, parsePnpmPackageKey, parsePnpmPackageKeyV9, normalizePnpmDepRef, normalizePnpmDepRefV9, } from "./pnpm-lock.js";
2
+ const EMPTY = Object.freeze([]);
3
+ function packageKey(name, version) {
4
+ return `${name}@${version ?? ""}`;
5
+ }
6
+ /**
7
+ * Reads the child keys declared by one lockfile entry. pnpm splits runtime
8
+ * dependencies across `dependencies` and `optionalDependencies`; both are real
9
+ * edges in the installed tree, so both count.
10
+ */
11
+ function childKeysOf(meta, normalize) {
12
+ const children = new Set();
13
+ for (const depMap of [meta?.dependencies, meta?.optionalDependencies]) {
14
+ if (!depMap || typeof depMap !== "object")
15
+ continue;
16
+ for (const [depName, depRef] of Object.entries(depMap)) {
17
+ const resolved = normalize(String(depName), depRef);
18
+ if (resolved)
19
+ children.add(resolved);
20
+ }
21
+ }
22
+ return [...children];
23
+ }
24
+ /**
25
+ * Builds the complete child-to-parents map for a pnpm lockfile.
26
+ *
27
+ * The parser already walks this same structure, but `collectPnpmPaths` caps it
28
+ * at five paths of at most ten segments per package. Reconstructing edges from
29
+ * those truncated paths loses routes on any sizeable tree, and a package whose
30
+ * surviving routes all traverse filtered-out packages ends up with no parent at
31
+ * all. This keeps every edge.
32
+ *
33
+ * Returns an empty graph for a lockfile it cannot read, so the caller falls
34
+ * back to path-derived behaviour rather than emitting an SBOM with no edges.
35
+ */
36
+ export function loadPnpmLockGraph(filePath) {
37
+ const parsed = readAndParsePnpmLock(filePath);
38
+ // pnpm v9 moved the dependency graph out of `packages` and into `snapshots`;
39
+ // `packages` there carries only resolution metadata and declares no edges.
40
+ const isV9 = !!parsed?.snapshots;
41
+ const section = isV9 ? parsed.snapshots : parsed?.packages;
42
+ const parseKey = isV9 ? parsePnpmPackageKeyV9 : parsePnpmPackageKey;
43
+ const normalize = isV9 ? normalizePnpmDepRefV9 : normalizePnpmDepRef;
44
+ const nodesById = new Map();
45
+ const nodeIdsByPackageKey = new Map();
46
+ const parentsByChild = new Map();
47
+ const register = (rawKey) => {
48
+ const ref = parseKey(String(rawKey));
49
+ if (!ref)
50
+ return null;
51
+ if (!nodesById.has(ref.key)) {
52
+ nodesById.set(ref.key, { name: ref.name, version: ref.version });
53
+ const pkgKey = packageKey(ref.name, ref.version);
54
+ const ids = nodeIdsByPackageKey.get(pkgKey);
55
+ if (ids)
56
+ ids.push(ref.key);
57
+ else
58
+ nodeIdsByPackageKey.set(pkgKey, [ref.key]);
59
+ }
60
+ return ref.key;
61
+ };
62
+ for (const [rawKey, meta] of Object.entries(section ?? {})) {
63
+ const parentId = register(rawKey);
64
+ if (!parentId)
65
+ continue;
66
+ for (const rawChild of childKeysOf(meta, normalize)) {
67
+ const childId = register(rawChild);
68
+ // A dependency that resolves to nothing in this lockfile, a workspace
69
+ // link or an unresolved optional, is not a node and cannot carry an edge.
70
+ if (!childId || childId === parentId)
71
+ continue;
72
+ const parents = parentsByChild.get(childId);
73
+ if (parents)
74
+ parents.add(parentId);
75
+ else
76
+ parentsByChild.set(childId, new Set([parentId]));
77
+ }
78
+ }
79
+ const frozenParents = new Map();
80
+ for (const [child, parents] of parentsByChild) {
81
+ frozenParents.set(child, Object.freeze([...parents]));
82
+ }
83
+ return {
84
+ nodeIdsFor(name, version) {
85
+ return nodeIdsByPackageKey.get(packageKey(name, version)) ?? EMPTY;
86
+ },
87
+ parentsFor(nodeId) {
88
+ return frozenParents.get(nodeId) ?? EMPTY;
89
+ },
90
+ getNode(nodeId) {
91
+ return nodesById.get(nodeId) ?? null;
92
+ },
93
+ };
94
+ }
@@ -55,7 +55,7 @@ function hasProjectImporterSections(document) {
55
55
  // parsed exactly once. The mtime/size key invalidates automatically after `--fix` rewrites
56
56
  // the lockfile, so a re-scan in the same process always sees the fresh contents.
57
57
  const parsedLockCache = new Map();
58
- function readAndParsePnpmLock(filePath) {
58
+ export function readAndParsePnpmLock(filePath) {
59
59
  const stat = fs.statSync(filePath);
60
60
  const cacheKey = `${filePath}::${stat.mtimeMs}::${stat.size}`;
61
61
  if (parsedLockCache.has(cacheKey))
@@ -285,7 +285,7 @@ function pathsEqual(left, right) {
285
285
  return false;
286
286
  return left.every((value, index) => value === right[index]);
287
287
  }
288
- function parsePnpmPackageKey(key) {
288
+ export function parsePnpmPackageKey(key) {
289
289
  const cleaned = key.replace(/^\//, "").split("(")[0];
290
290
  const match = cleaned.match(/^(@?[^/]+(?:\/[^/]+)?)\/([^/]+)$/);
291
291
  if (!match)
@@ -293,7 +293,7 @@ function parsePnpmPackageKey(key) {
293
293
  const [, name, version] = match;
294
294
  return { key, name, version };
295
295
  }
296
- function parsePnpmPackageKeyV9(key) {
296
+ export function parsePnpmPackageKeyV9(key) {
297
297
  // strip leading slash (pnpm v9 can emit /@babel/core@7.20.0) then peer-dep suffix (pkg@1.0.0(peer@2.0.0))
298
298
  const cleaned = key.replace(/^\//, "").split("(")[0];
299
299
  const idx = cleaned.lastIndexOf("@");
@@ -305,7 +305,7 @@ function parsePnpmPackageKeyV9(key) {
305
305
  return null;
306
306
  return { key: cleaned, name, version };
307
307
  }
308
- function normalizePnpmDepRef(depName, depRef) {
308
+ export function normalizePnpmDepRef(depName, depRef) {
309
309
  if (typeof depRef === "string") {
310
310
  const cleaned = depRef.replace(/^link:/, "").replace(/^workspace:/, "").split("(")[0];
311
311
  if (!cleaned || cleaned.startsWith(".") || cleaned.startsWith(".."))
@@ -323,7 +323,7 @@ function normalizePnpmDepRef(depName, depRef) {
323
323
  }
324
324
  return null;
325
325
  }
326
- function normalizePnpmDepRefV9(depName, depRef) {
326
+ export function normalizePnpmDepRefV9(depName, depRef) {
327
327
  if (typeof depRef === "string") {
328
328
  const cleaned = depRef.replace(/^link:/, "").replace(/^workspace:/, "").replace(/^\//, "").split("(")[0];
329
329
  if (!cleaned || cleaned.startsWith(".") || cleaned.startsWith(".."))
@@ -8,6 +8,9 @@ export function upsertPackage(map, candidate) {
8
8
  }
9
9
  existing.dev = existing.dev && candidate.dev;
10
10
  existing.paths = uniquePathArrays([...(existing.paths ?? []), ...(candidate.paths ?? [])]).slice(0, 5);
11
+ // The same name@version can appear at several lockfile paths; keep the first
12
+ // license we see rather than losing it if a later entry omits the field.
13
+ existing.license ??= candidate.license;
11
14
  }
12
15
  export function normalizeNodeModulesPath(pkgPath) {
13
16
  const parts = pkgPath.split("/").filter(Boolean);
@@ -0,0 +1,148 @@
1
+ import fs from "node:fs";
2
+ import { parse as parseYarnLock } from "yarn-lockfile";
3
+ import { isYarnBerry, parseBerryDependencies, parseYarnPackageKey } from "./yarn-lock.js";
4
+ const EMPTY = Object.freeze([]);
5
+ /**
6
+ * Builds the index for a Berry (v2+) lockfile.
7
+ *
8
+ * Berry writes one block per entry, with a `resolution:` line carrying the
9
+ * concrete `name@npm:version`. The block header lists every range that resolves
10
+ * to it, comma separated.
11
+ */
12
+ function buildBerryIndex(content) {
13
+ const selectorToKey = new Map();
14
+ const graph = new Map();
15
+ const blocks = content.split(/\n\n+/);
16
+ for (const block of blocks) {
17
+ const lines = block.trim().split("\n");
18
+ if (!lines[0] || lines[0].startsWith("__metadata"))
19
+ continue;
20
+ const resolutionLine = lines.find(line => line.trim().startsWith("resolution:"));
21
+ const resolution = resolutionLine?.match(/resolution:\s+"(.+)"/)?.[1];
22
+ if (!resolution)
23
+ continue;
24
+ const npmIndex = resolution.lastIndexOf("@npm:");
25
+ if (npmIndex < 0)
26
+ continue;
27
+ const name = resolution.slice(0, npmIndex);
28
+ const version = resolution.slice(npmIndex + 5);
29
+ if (!name || !version)
30
+ continue;
31
+ const canonicalKey = `${name}@${version}`;
32
+ const header = lines[0].trim().replace(/:$/, "").replace(/^"|"$/g, "");
33
+ for (const selector of header.split(",").map(part => part.trim()).filter(Boolean)) {
34
+ selectorToKey.set(selector, canonicalKey);
35
+ }
36
+ }
37
+ for (const block of blocks) {
38
+ const lines = block.trim().split("\n");
39
+ if (!lines[0] || lines[0].startsWith("__metadata"))
40
+ continue;
41
+ const header = lines[0].trim().replace(/:$/, "").replace(/^"|"$/g, "");
42
+ const firstSelector = header.split(",").map(part => part.trim()).find(Boolean);
43
+ const canonicalKey = firstSelector ? selectorToKey.get(firstSelector) : undefined;
44
+ if (!canonicalKey)
45
+ continue;
46
+ const children = new Set();
47
+ for (const [depName, depRange] of Object.entries(parseBerryDependencies(block))) {
48
+ const childKey = selectorToKey.get(`${depName}@${depRange}`) ?? selectorToKey.get(`${depName}@npm:${depRange}`);
49
+ if (childKey)
50
+ children.add(childKey);
51
+ }
52
+ graph.set(canonicalKey, [...children]);
53
+ }
54
+ return { selectorToKey, graph };
55
+ }
56
+ /**
57
+ * Builds the index for a classic (v1) lockfile, which the `yarn-lockfile`
58
+ * parser hands back as an object keyed by comma-separated ranges.
59
+ */
60
+ function buildClassicIndex(parsed) {
61
+ const selectorToKey = new Map();
62
+ const graph = new Map();
63
+ const entries = Object.entries(parsed?.object ?? {});
64
+ for (const [selectorKey, meta] of entries) {
65
+ const version = meta?.version;
66
+ if (!version)
67
+ continue;
68
+ const selectors = String(selectorKey).split(",").map(part => part.trim()).filter(Boolean);
69
+ const atIndex = selectors[0]?.lastIndexOf("@") ?? -1;
70
+ if (atIndex <= 0)
71
+ continue;
72
+ const canonicalKey = `${selectors[0].slice(0, atIndex)}@${version}`;
73
+ for (const selector of selectors)
74
+ selectorToKey.set(selector, canonicalKey);
75
+ }
76
+ for (const [selectorKey, meta] of entries) {
77
+ const version = meta?.version;
78
+ if (!version)
79
+ continue;
80
+ const selectors = String(selectorKey).split(",").map(part => part.trim()).filter(Boolean);
81
+ const atIndex = selectors[0]?.lastIndexOf("@") ?? -1;
82
+ if (atIndex <= 0)
83
+ continue;
84
+ const canonicalKey = `${selectors[0].slice(0, atIndex)}@${version}`;
85
+ const children = new Set();
86
+ const deps = meta?.dependencies;
87
+ if (deps && typeof deps === "object") {
88
+ for (const [depName, depRange] of Object.entries(deps)) {
89
+ const childKey = selectorToKey.get(`${depName}@${depRange}`);
90
+ if (childKey)
91
+ children.add(childKey);
92
+ }
93
+ }
94
+ graph.set(canonicalKey, [...children]);
95
+ }
96
+ return { selectorToKey, graph };
97
+ }
98
+ /**
99
+ * Builds the complete child-to-parents map for a `yarn.lock`, covering both the
100
+ * classic and Berry formats.
101
+ *
102
+ * Returns null for a lockfile it cannot read, so the caller falls back to
103
+ * path-derived behaviour rather than emitting an SBOM with no edges.
104
+ */
105
+ export function loadYarnLockGraph(filePath) {
106
+ let content;
107
+ try {
108
+ content = fs.readFileSync(filePath, "utf8");
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ let index;
114
+ if (isYarnBerry(content)) {
115
+ index = buildBerryIndex(content);
116
+ }
117
+ else {
118
+ const parsed = parseYarnLock(content);
119
+ if (!parsed?.object)
120
+ return null;
121
+ index = buildClassicIndex(parsed);
122
+ }
123
+ if (index.graph.size === 0)
124
+ return null;
125
+ const parentsByKey = new Map();
126
+ for (const [parentKey, childKeys] of index.graph) {
127
+ for (const childKey of childKeys) {
128
+ const parents = parentsByKey.get(childKey);
129
+ if (!parents)
130
+ parentsByKey.set(childKey, [parentKey]);
131
+ else if (!parents.includes(parentKey))
132
+ parents.push(parentKey);
133
+ }
134
+ }
135
+ return {
136
+ // Canonical keys are already `name@version`, so one name and version is one
137
+ // node, unlike pnpm and Bun where several keys can describe the same package.
138
+ nodeIdsFor: (name, version) => {
139
+ const key = `${name}@${version ?? ""}`;
140
+ return index.graph.has(key) || parentsByKey.has(key) ? [key] : EMPTY;
141
+ },
142
+ parentsFor: nodeId => parentsByKey.get(nodeId) ?? EMPTY,
143
+ getNode: nodeId => {
144
+ const parsedKey = parseYarnPackageKey(nodeId);
145
+ return parsedKey ? { name: parsedKey.name, version: parsedKey.version } : null;
146
+ },
147
+ };
148
+ }
@@ -127,7 +127,7 @@ function readWorkspacePackages(filePath, rootPkg) {
127
127
  }
128
128
  return result;
129
129
  }
130
- function isYarnBerry(content) {
130
+ export function isYarnBerry(content) {
131
131
  return content.startsWith('__metadata:') || content.includes('\n__metadata:');
132
132
  }
133
133
  function pathsEqual(left, right) {
@@ -135,7 +135,7 @@ function pathsEqual(left, right) {
135
135
  return false;
136
136
  return left.every((value, index) => value === right[index]);
137
137
  }
138
- function parseYarnPackageKey(key) {
138
+ export function parseYarnPackageKey(key) {
139
139
  const idx = key.lastIndexOf("@");
140
140
  if (idx <= 0)
141
141
  return null;
@@ -222,7 +222,7 @@ function loadSeeds(filePath, selectorToKey, map, taggedPathsByKey, prodFallbackK
222
222
  }
223
223
  return seeds;
224
224
  }
225
- function parseBerryDependencies(block) {
225
+ export function parseBerryDependencies(block) {
226
226
  const dependencies = {};
227
227
  const lines = block.split("\n");
228
228
  let inDependencies = false;