cve-lite-cli 1.41.0 → 1.41.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/output/formatters.js +5 -3
- package/dist/output/html-reporter.js +2 -1
- package/dist/output/override-fix-command.js +5 -7
- package/dist/overrides/detectors/pd001-override-only-phantom.js +2 -3
- package/dist/overrides/detectors/pd002-transitive-only-phantom.js +2 -3
- package/dist/overrides/detectors/phantom-utils.js +5 -0
- package/dist/overrides/parsing/package-json.js +1 -1
- package/dist/overrides/parsing/registry.js +19 -69
- package/dist/parsers/npm-alias-resolution.js +248 -0
- package/dist/parsers/npm-lock-graph.js +77 -33
- package/dist/parsers/yarn-lock-graph.js +31 -15
- package/dist/parsers/yarn-lock.js +91 -23
- package/dist/remediation/fix-commands.js +8 -9
- package/dist/remediation/npm-registry.js +10 -2
- package/dist/remediation/transitive-chain-resolver.js +2 -2
- package/dist/scan/override-audit.js +6 -4
- package/dist/scanner.js +8 -1
- package/dist/utils/checked-address-policy.js +44 -0
- package/dist/utils/network.js +1 -0
- package/dist/utils/osv-fetch.js +12 -48
- package/dist/utils/package-json.js +1 -0
- package/dist/utils/registry-config.js +49 -2
- package/dist/utils/registry-fetch.js +42 -0
- package/dist/utils/shell-quote.js +12 -0
- package/package.json +1 -1
|
@@ -6,6 +6,7 @@ import { inferSeverity } from "../osv/severity.js";
|
|
|
6
6
|
import { getPrimaryParent, getRootDependencies, isUnconfirmedFix } from "../utils/finding.js";
|
|
7
7
|
import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
|
|
8
8
|
import { pluralize, isOutputStdout } from "../utils/string.js";
|
|
9
|
+
import { shellQuote } from "../utils/shell-quote.js";
|
|
9
10
|
import { hasMaliciousAdvisory } from "../utils/vuln.js";
|
|
10
11
|
import { computePrioritySignal } from "../utils/priority-signal.js";
|
|
11
12
|
import { computeContextualSignals } from "../utils/contextual-signals.js";
|
|
@@ -113,10 +114,11 @@ export function getRecommendedAction(finding) {
|
|
|
113
114
|
// a degenerate length-2 chain (project -> vulnerable, common when the
|
|
114
115
|
// package is hoisted to top-level node_modules). The advice is the same
|
|
115
116
|
// either way - inspect the lockfile or run `<pm> ls` to find the parent.
|
|
117
|
+
const inspectMessage = `No parent dependency was identified for ${finding.pkg.name} in the lockfile. Run \`npm ls ${shellQuote(finding.pkg.name)}\` (or your package manager equivalent) to find which package pulls it in`;
|
|
116
118
|
if (directTarget) {
|
|
117
|
-
return
|
|
119
|
+
return `${inspectMessage}, then upgrade toward ${directTarget}+.`;
|
|
118
120
|
}
|
|
119
|
-
return
|
|
121
|
+
return `${inspectMessage}.`;
|
|
120
122
|
}
|
|
121
123
|
export function summarizeRisk(finding) {
|
|
122
124
|
if (finding.maliciousUnverifiable) {
|
|
@@ -228,7 +230,7 @@ export function summarizeNextAction(finding) {
|
|
|
228
230
|
return `Upgrade ${parent} - no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
|
|
229
231
|
}
|
|
230
232
|
if (directTarget) {
|
|
231
|
-
return `No parent identified in the lockfile. Run \`npm ls ${finding.pkg.name}\` to find the parent, then upgrade toward ${directTarget}+.`;
|
|
233
|
+
return `No parent identified in the lockfile. Run \`npm ls ${shellQuote(finding.pkg.name)}\` to find the parent, then upgrade toward ${directTarget}+.`;
|
|
232
234
|
}
|
|
233
235
|
return `Inspect the parent dependency chain for ${finding.pkg.name} and choose the safest available upgrade.`;
|
|
234
236
|
}
|
|
@@ -6,6 +6,7 @@ import { serializeFinding, summarizeNextAction, summarizeRisk, formatCooldownWar
|
|
|
6
6
|
import { loadLogoDataUri } from "./logos.js";
|
|
7
7
|
import { isBreakingUpgrade } from "../utils/version.js";
|
|
8
8
|
import { pluralize } from "../utils/string.js";
|
|
9
|
+
import { shellQuote } from "../utils/shell-quote.js";
|
|
9
10
|
import { MAL_GIT_SOURCE_PINNED_DISPLAY, MAL_GIT_SOURCE_FLOATING_DISPLAY, severityOrder } from "../constants.js";
|
|
10
11
|
import { hasMaliciousAdvisory } from "../utils/vuln.js";
|
|
11
12
|
import { renderOverrideFindingsHtml } from "./override-findings-html.js";
|
|
@@ -739,7 +740,7 @@ function renderTransitiveContextCol(finding) {
|
|
|
739
740
|
return `<div class="detail-col" style="max-width:200px">
|
|
740
741
|
<h4>Context</h4>
|
|
741
742
|
<span class="tier-err">✕ No parent identified</span>
|
|
742
|
-
<p style="font-size:12px;color:var(--text-2);margin-top:4px">Run <code>npm ls ${escapeHtml(finding.package)}</code> to find which package pulls it in.</p>
|
|
743
|
+
<p style="font-size:12px;color:var(--text-2);margin-top:4px">Run <code>npm ls ${escapeHtml(shellQuote(finding.package))}</code> to find which package pulls it in.</p>
|
|
743
744
|
</div>`;
|
|
744
745
|
}
|
|
745
746
|
export function renderCompletenessBanner(completeness) {
|
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
import { OVERRIDES_COMMAND } from "../constants.js";
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// project-relative target stays runnable when it is copied out.
|
|
2
|
+
import { quoteShellPath } from "../utils/shell-quote.js";
|
|
3
|
+
// HTML callers pass a project-relative path, and terminal callers pass a
|
|
4
|
+
// cwd-relative path. An empty target or "." needs no positional argument.
|
|
6
5
|
export function overrideCommandTargetSuffix(commandTarget) {
|
|
7
|
-
|
|
8
|
-
return normalized && normalized !== "." ? ` ${normalized}` : "";
|
|
6
|
+
return commandTarget && commandTarget !== "." ? ` ${quoteShellPath(commandTarget)}` : "";
|
|
9
7
|
}
|
|
10
8
|
export function buildOverrideFixCommand(runnableCommand, commandTarget) {
|
|
11
9
|
const suffix = overrideCommandTargetSuffix(commandTarget);
|
|
12
|
-
return runnableCommand.replace(OVERRIDES_COMMAND, `cve-lite${suffix} overrides`);
|
|
10
|
+
return runnableCommand.replace(OVERRIDES_COMMAND, () => `cve-lite${suffix} overrides`);
|
|
13
11
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { formatPhantomInstallCommand, getDeclaredPackages, undeclaredImportFiles } from "./phantom-utils.js";
|
|
2
2
|
const RULE_ID = "PD001";
|
|
3
3
|
export function detect(ctx) {
|
|
4
4
|
if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
|
|
@@ -7,7 +7,6 @@ export function detect(ctx) {
|
|
|
7
7
|
return [];
|
|
8
8
|
const declared = getDeclaredPackages(ctx.packageJson);
|
|
9
9
|
const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
|
|
10
|
-
const cmd = installCmd(ctx.packageManager);
|
|
11
10
|
const findings = [];
|
|
12
11
|
for (const [pkgName, importedIn] of ctx.importedPackageNames) {
|
|
13
12
|
if (!overrideNames.has(pkgName))
|
|
@@ -25,7 +24,7 @@ export function detect(ctx) {
|
|
|
25
24
|
message: `${pkgName} is imported in source but only present via an override pin - declare it as a dependency`,
|
|
26
25
|
details: `Imported in: ${shown.join(", ")}${extra}. ` +
|
|
27
26
|
`In pnpm strict mode (default on Vercel), override-only packages are not importable and will cause a deploy failure. ` +
|
|
28
|
-
`Run: ${
|
|
27
|
+
`Run: ${formatPhantomInstallCommand(ctx.packageManager, pkgName)}`,
|
|
29
28
|
references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD001.md"],
|
|
30
29
|
});
|
|
31
30
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { formatPhantomInstallCommand, getDeclaredPackages, undeclaredImportFiles } from "./phantom-utils.js";
|
|
2
2
|
const RULE_ID = "PD002";
|
|
3
3
|
export function detect(ctx) {
|
|
4
4
|
if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
|
|
@@ -7,7 +7,6 @@ export function detect(ctx) {
|
|
|
7
7
|
return [];
|
|
8
8
|
const declared = getDeclaredPackages(ctx.packageJson);
|
|
9
9
|
const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
|
|
10
|
-
const cmd = installCmd(ctx.packageManager);
|
|
11
10
|
const findings = [];
|
|
12
11
|
for (const [pkgName, importedIn] of ctx.importedPackageNames) {
|
|
13
12
|
if (overrideNames.has(pkgName))
|
|
@@ -27,7 +26,7 @@ export function detect(ctx) {
|
|
|
27
26
|
message: `${pkgName} is imported in source but only present as a transitive dependency - declare it explicitly`,
|
|
28
27
|
details: `Imported in: ${shown.join(", ")}${extra}. ` +
|
|
29
28
|
`If the parent package drops or changes this dependency, your code will break without warning. ` +
|
|
30
|
-
`Run: ${
|
|
29
|
+
`Run: ${formatPhantomInstallCommand(ctx.packageManager, pkgName)}`,
|
|
31
30
|
references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD002.md"],
|
|
32
31
|
});
|
|
33
32
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { shellQuote } from "../../utils/shell-quote.js";
|
|
1
2
|
export function getDeclaredPackages(packageJson) {
|
|
2
3
|
const declared = new Set();
|
|
3
4
|
for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
|
|
@@ -48,3 +49,7 @@ export function installCmd(pm) {
|
|
|
48
49
|
return "bun add";
|
|
49
50
|
return "npm install";
|
|
50
51
|
}
|
|
52
|
+
/** Format a copyable phantom-dependency install command with shell-quoted package name. */
|
|
53
|
+
export function formatPhantomInstallCommand(pm, pkgName) {
|
|
54
|
+
return `${installCmd(pm)} ${shellQuote(pkgName)}`;
|
|
55
|
+
}
|
|
@@ -49,7 +49,7 @@ export function bareName(overrideKey) {
|
|
|
49
49
|
* or -1 if there is none. For scoped names the leading `@` (index 0) is the
|
|
50
50
|
* scope, not a specifier, so we look past it.
|
|
51
51
|
*/
|
|
52
|
-
function specifierAt(selector) {
|
|
52
|
+
export function specifierAt(selector) {
|
|
53
53
|
if (selector.startsWith('@')) {
|
|
54
54
|
return selector.indexOf('@', 1);
|
|
55
55
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { fetchRegistryMetadata } from '../../utils/registry-fetch.js';
|
|
1
2
|
import { compareVersions, isPreReleaseVersion } from '../../utils/version.js';
|
|
2
3
|
async function classify(attempt, parse) {
|
|
3
4
|
let res;
|
|
@@ -19,33 +20,21 @@ async function classify(attempt, parse) {
|
|
|
19
20
|
return { kind: "failed" };
|
|
20
21
|
}
|
|
21
22
|
}
|
|
22
|
-
/**
|
|
23
|
-
* Fetch the `dist-tags` map for `pkgName` from the npm registry.
|
|
24
|
-
*
|
|
25
|
-
* Returns null on any failure (network error, non-200, parse error, timeout).
|
|
26
|
-
* The caller surfaces a `skippedDetectors` note when this returns null for a
|
|
27
|
-
* rule that depends on registry data.
|
|
28
|
-
*
|
|
29
|
-
* Per scan, callers should batch-fetch all needed packages in parallel and
|
|
30
|
-
* cache the result on `Context.registryDistTags`. This function is single-shot;
|
|
31
|
-
* caching/batching is the scanner's responsibility.
|
|
32
|
-
*/
|
|
33
23
|
/** Shared request shape for both lookups. */
|
|
34
24
|
async function packumentOutcome(pkgName, opts, parse) {
|
|
35
25
|
const baseUrl = opts.baseUrl ?? 'https://registry.npmjs.org';
|
|
36
26
|
const timeoutMs = opts.timeoutMs ?? 5000;
|
|
37
|
-
const
|
|
38
|
-
const url = `${baseUrl}/${encodeRegistryPath(pkgName)}`;
|
|
27
|
+
const url = `${baseUrl.replace(/\/+$/, "")}/${encodeRegistryPath(pkgName)}`;
|
|
39
28
|
const controller = new AbortController();
|
|
40
29
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
41
30
|
try {
|
|
42
|
-
return await classify(() =>
|
|
31
|
+
return await classify(() => fetchRegistryMetadata(baseUrl, url, opts.allowPrivate ?? false, {
|
|
43
32
|
signal: controller.signal,
|
|
44
33
|
headers: {
|
|
45
34
|
Accept: 'application/vnd.npm.install-v1+json',
|
|
46
35
|
'User-Agent': 'override-audit-cli',
|
|
47
36
|
},
|
|
48
|
-
}), parse);
|
|
37
|
+
}, opts.fetchImpl), parse);
|
|
49
38
|
}
|
|
50
39
|
finally {
|
|
51
40
|
clearTimeout(timer);
|
|
@@ -67,32 +56,20 @@ async function versionsOutcome(pkgName, opts) {
|
|
|
67
56
|
.sort(compareVersions);
|
|
68
57
|
});
|
|
69
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Fetch the `dist-tags` map for `pkgName` from the npm registry.
|
|
61
|
+
*
|
|
62
|
+
* Returns null on any failure (network error, non-200, parse error, timeout).
|
|
63
|
+
* The caller surfaces a `skippedDetectors` note when this returns null for a
|
|
64
|
+
* rule that depends on registry data.
|
|
65
|
+
*
|
|
66
|
+
* Per scan, callers should batch-fetch all needed packages in parallel and
|
|
67
|
+
* cache the result on `Context.registryDistTags`. This function is single-shot;
|
|
68
|
+
* caching/batching is the scanner's responsibility.
|
|
69
|
+
*/
|
|
70
70
|
export async function fetchDistTags(pkgName, opts = {}) {
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
74
|
-
const url = `${baseUrl}/${encodeRegistryPath(pkgName)}`;
|
|
75
|
-
const controller = new AbortController();
|
|
76
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
77
|
-
try {
|
|
78
|
-
const res = await fetchImpl(url, {
|
|
79
|
-
signal: controller.signal,
|
|
80
|
-
headers: {
|
|
81
|
-
Accept: 'application/vnd.npm.install-v1+json',
|
|
82
|
-
'User-Agent': 'override-audit-cli',
|
|
83
|
-
},
|
|
84
|
-
});
|
|
85
|
-
if (!res.ok)
|
|
86
|
-
return null;
|
|
87
|
-
const body = await res.json();
|
|
88
|
-
return body['dist-tags'] ?? null;
|
|
89
|
-
}
|
|
90
|
-
catch {
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
finally {
|
|
94
|
-
clearTimeout(timer);
|
|
95
|
-
}
|
|
71
|
+
const outcome = await distTagsOutcome(pkgName, opts);
|
|
72
|
+
return outcome.kind === "ok" ? outcome.value : null;
|
|
96
73
|
}
|
|
97
74
|
/**
|
|
98
75
|
* Fetch dist-tags for many packages concurrently. Failures collapse to null
|
|
@@ -122,35 +99,8 @@ export async function fetchDistTagsBatch(pkgNames, opts = {}) {
|
|
|
122
99
|
* Returns null on any failure, matching `fetchDistTags`.
|
|
123
100
|
*/
|
|
124
101
|
export async function fetchVersions(pkgName, opts = {}) {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
128
|
-
const url = `${baseUrl}/${encodeRegistryPath(pkgName)}`;
|
|
129
|
-
const controller = new AbortController();
|
|
130
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
131
|
-
try {
|
|
132
|
-
const res = await fetchImpl(url, {
|
|
133
|
-
signal: controller.signal,
|
|
134
|
-
headers: {
|
|
135
|
-
Accept: 'application/vnd.npm.install-v1+json',
|
|
136
|
-
'User-Agent': 'override-audit-cli',
|
|
137
|
-
},
|
|
138
|
-
});
|
|
139
|
-
if (!res.ok)
|
|
140
|
-
return null;
|
|
141
|
-
const body = await res.json();
|
|
142
|
-
if (!body.versions)
|
|
143
|
-
return null;
|
|
144
|
-
return Object.keys(body.versions)
|
|
145
|
-
.filter((v) => !isPreReleaseVersion(v))
|
|
146
|
-
.sort(compareVersions);
|
|
147
|
-
}
|
|
148
|
-
catch {
|
|
149
|
-
return null;
|
|
150
|
-
}
|
|
151
|
-
finally {
|
|
152
|
-
clearTimeout(timer);
|
|
153
|
-
}
|
|
102
|
+
const outcome = await versionsOutcome(pkgName, opts);
|
|
103
|
+
return outcome.kind === "ok" ? outcome.value : null;
|
|
154
104
|
}
|
|
155
105
|
/**
|
|
156
106
|
* Fetch version lists for many packages concurrently. Per-package failures
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { bareName, specifierAt } from "../overrides/parsing/package-json.js";
|
|
4
|
+
import { isGitSource } from "../utils/advisory.js";
|
|
5
|
+
import { isRecord } from "../utils/package-json.js";
|
|
6
|
+
import { npmAliasRegistryName } from "../utils/package-identity.js";
|
|
7
|
+
import { isValidRange, satisfiesRange } from "../utils/version.js";
|
|
8
|
+
/**
|
|
9
|
+
* Resolve true npm registry identities onto lockfile graph nodes without
|
|
10
|
+
* re-attributing non-registry git/tarball packages or un-installed peers.
|
|
11
|
+
*/
|
|
12
|
+
export function resolveNpmLockAliasIdentities(ctx) {
|
|
13
|
+
const overrideRules = loadOverrideAliasRules(ctx.filePath, ctx.rootMeta);
|
|
14
|
+
const legacyAliasByPath = collectLegacyAliasRegistryNames(ctx.rawLegacyDependencies);
|
|
15
|
+
for (const node of ctx.nodesById.values()) {
|
|
16
|
+
const registryName = resolveNodeRegistryName(node, ctx, overrideRules, legacyAliasByPath);
|
|
17
|
+
if (registryName) {
|
|
18
|
+
node.registryName = registryName;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Format the canonical key tracking a fallback edge added from `peerDependencies`. */
|
|
23
|
+
export function peerFallbackEdgeKey(parentNodeId, childNodeId) {
|
|
24
|
+
return `${parentNodeId}\u0000${childNodeId}`;
|
|
25
|
+
}
|
|
26
|
+
function collectRegularDeclaredRanges(node, ctx) {
|
|
27
|
+
const ranges = [];
|
|
28
|
+
if (ctx.rootEntryNodeIds.has(node.id)) {
|
|
29
|
+
const rootRange = ctx.rootRanges[node.name];
|
|
30
|
+
if (rootRange)
|
|
31
|
+
ranges.push(rootRange);
|
|
32
|
+
}
|
|
33
|
+
for (const parentId of ctx.parentNodeIdsByChildNodeId.get(node.id) ?? []) {
|
|
34
|
+
if (ctx.peerFallbackEdgeKeys.has(peerFallbackEdgeKey(parentId, node.id)))
|
|
35
|
+
continue;
|
|
36
|
+
const range = ctx.rangeByParentNodeId.get(parentId)?.get(node.name);
|
|
37
|
+
if (range)
|
|
38
|
+
ranges.push(range);
|
|
39
|
+
}
|
|
40
|
+
return ranges;
|
|
41
|
+
}
|
|
42
|
+
function resolveNodeRegistryName(node, ctx, overrideRules, legacyAliasByPath) {
|
|
43
|
+
const regularDeclaredRanges = collectRegularDeclaredRanges(node, ctx);
|
|
44
|
+
const manifestName = ctx.manifestNameByNodeId.get(node.id);
|
|
45
|
+
const resolvedUrl = ctx.resolvedUrlByNodeId.get(node.id);
|
|
46
|
+
// 1. Explicit `npm:` spec on root or regular parent dependencies.
|
|
47
|
+
const explicitAlias = regularDeclaredRanges
|
|
48
|
+
.map(npmAliasRegistryName)
|
|
49
|
+
.find((name) => name && name !== node.name);
|
|
50
|
+
if (explicitAlias)
|
|
51
|
+
return explicitAlias;
|
|
52
|
+
// 2. Lockfile v2 legacy `dependencies` entry.
|
|
53
|
+
const legacyAlias = legacyAliasByPath.get(node.packagePath);
|
|
54
|
+
if (legacyAlias && legacyAlias !== node.name && (!manifestName || manifestName === legacyAlias)) {
|
|
55
|
+
return legacyAlias;
|
|
56
|
+
}
|
|
57
|
+
// Remaining paths rely on a differing installed manifest `name`.
|
|
58
|
+
if (!manifestName || manifestName === node.name)
|
|
59
|
+
return null;
|
|
60
|
+
// 3. Peer-derived `npm:` alias: only trust when the node's lockfile manifest `name`
|
|
61
|
+
// matches the alias target, so `--legacy-peer-deps` or optional peers cannot
|
|
62
|
+
// substitute an alias identity onto a different real package installed in that slot.
|
|
63
|
+
if (!isGitSource({ resolvedUrl }) &&
|
|
64
|
+
(regularDeclaredRanges.length === 0 || regularDeclaredRanges.every(looksLikeRegistryVersionSpec))) {
|
|
65
|
+
const peerRanges = ctx.peerRangesByChildNodeId.get(node.id) ?? [];
|
|
66
|
+
const peerAlias = peerRanges
|
|
67
|
+
.map(npmAliasRegistryName)
|
|
68
|
+
.find((name) => name === manifestName);
|
|
69
|
+
if (peerAlias)
|
|
70
|
+
return peerAlias;
|
|
71
|
+
}
|
|
72
|
+
// 4. Configured `overrides` (package.json or root lockfile metadata).
|
|
73
|
+
if (!isGitSource({ resolvedUrl })) {
|
|
74
|
+
const matchedRule = overrideRules.find((rule) => rule.target.name === node.name &&
|
|
75
|
+
rule.registryName === manifestName &&
|
|
76
|
+
matchesAncestorChain(node.id, rule.parentChain, ctx));
|
|
77
|
+
if (matchedRule)
|
|
78
|
+
return matchedRule.registryName;
|
|
79
|
+
}
|
|
80
|
+
// 5. Standalone v3 lockfiles omit `overrides` and replace the child spec only in
|
|
81
|
+
// node metadata; accept standard registry tarball layouts (including private
|
|
82
|
+
// mirrors) when every regular parent spec is a registry range/tag (#1450).
|
|
83
|
+
if (!isGitSource({ resolvedUrl }) &&
|
|
84
|
+
regularDeclaredRanges.length > 0 &&
|
|
85
|
+
regularDeclaredRanges.every(looksLikeRegistryVersionSpec) &&
|
|
86
|
+
isRegistryTarballForPackage(resolvedUrl, manifestName, node.version)) {
|
|
87
|
+
return manifestName;
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
function loadOverrideAliasRules(lockfilePath, rootMeta) {
|
|
92
|
+
const pkgJson = readJsonObject(path.join(path.dirname(lockfilePath), "package.json"));
|
|
93
|
+
const rootManifestDeps = collectRootManifestDeps(rootMeta, pkgJson);
|
|
94
|
+
const rules = [];
|
|
95
|
+
walkOverrideAliasRules(pkgJson?.overrides, [], rootManifestDeps, rules);
|
|
96
|
+
walkOverrideAliasRules(rootMeta?.overrides, [], rootManifestDeps, rules);
|
|
97
|
+
return rules;
|
|
98
|
+
}
|
|
99
|
+
function readJsonObject(filePath) {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
102
|
+
return isRecord(parsed) ? parsed : null;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function collectRootManifestDeps(rootMeta, pkgJson) {
|
|
109
|
+
const deps = {};
|
|
110
|
+
const sections = ["peerDependencies", "devDependencies", "optionalDependencies", "dependencies"];
|
|
111
|
+
for (const source of [rootMeta, pkgJson]) {
|
|
112
|
+
if (!source)
|
|
113
|
+
continue;
|
|
114
|
+
for (const sectionName of sections) {
|
|
115
|
+
const section = source[sectionName];
|
|
116
|
+
if (!isRecord(section))
|
|
117
|
+
continue;
|
|
118
|
+
for (const [name, spec] of Object.entries(section)) {
|
|
119
|
+
if (typeof spec === "string" && spec)
|
|
120
|
+
deps[name] = spec;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return deps;
|
|
125
|
+
}
|
|
126
|
+
function walkOverrideAliasRules(node, ancestors, rootManifestDeps, rules) {
|
|
127
|
+
if (!isRecord(node))
|
|
128
|
+
return;
|
|
129
|
+
for (const [key, value] of Object.entries(node)) {
|
|
130
|
+
if (key === ".") {
|
|
131
|
+
if (typeof value === "string" && ancestors.length > 0) {
|
|
132
|
+
const registryName = resolveOverrideAliasRegistryName(value, rootManifestDeps);
|
|
133
|
+
const target = ancestors[ancestors.length - 1];
|
|
134
|
+
if (registryName && target.name) {
|
|
135
|
+
rules.push({
|
|
136
|
+
parentChain: ancestors.slice(0, -1),
|
|
137
|
+
target,
|
|
138
|
+
registryName,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const selector = splitOverrideSelector(key);
|
|
145
|
+
if (!selector.name)
|
|
146
|
+
continue;
|
|
147
|
+
if (typeof value === "string") {
|
|
148
|
+
const registryName = resolveOverrideAliasRegistryName(value, rootManifestDeps);
|
|
149
|
+
if (registryName) {
|
|
150
|
+
rules.push({ parentChain: ancestors, target: selector, registryName });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else if (isRecord(value)) {
|
|
154
|
+
walkOverrideAliasRules(value, [...ancestors, selector], rootManifestDeps, rules);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function splitOverrideSelector(key) {
|
|
159
|
+
const trimmed = key.trim();
|
|
160
|
+
const at = specifierAt(trimmed);
|
|
161
|
+
if (at === -1)
|
|
162
|
+
return { name: trimmed };
|
|
163
|
+
const name = bareName(trimmed);
|
|
164
|
+
const range = trimmed.slice(at + 1).trim();
|
|
165
|
+
return range ? { name, range } : { name };
|
|
166
|
+
}
|
|
167
|
+
function resolveOverrideAliasRegistryName(rawSpec, rootManifestDeps) {
|
|
168
|
+
const trimmed = rawSpec.trim();
|
|
169
|
+
const resolved = trimmed.startsWith("$") ? rootManifestDeps[trimmed.slice(1)] : trimmed;
|
|
170
|
+
return npmAliasRegistryName(resolved);
|
|
171
|
+
}
|
|
172
|
+
function matchesAncestorChain(childNodeId, parentChain, ctx) {
|
|
173
|
+
if (parentChain.length === 0)
|
|
174
|
+
return true;
|
|
175
|
+
const visited = new Set();
|
|
176
|
+
const stack = [];
|
|
177
|
+
for (const parentId of ctx.parentNodeIdsByChildNodeId.get(childNodeId) ?? []) {
|
|
178
|
+
stack.push({ currentId: parentId, chainIndex: parentChain.length - 1 });
|
|
179
|
+
}
|
|
180
|
+
while (stack.length > 0) {
|
|
181
|
+
const { currentId, chainIndex } = stack.pop();
|
|
182
|
+
const visitKey = `${currentId}\u0000${chainIndex}`;
|
|
183
|
+
if (visited.has(visitKey))
|
|
184
|
+
continue;
|
|
185
|
+
visited.add(visitKey);
|
|
186
|
+
const parentNode = ctx.nodesById.get(currentId);
|
|
187
|
+
if (!parentNode)
|
|
188
|
+
continue;
|
|
189
|
+
const selector = parentChain[chainIndex];
|
|
190
|
+
const parentVersion = parentNode.version ?? ctx.ancestorVersionByNodeId.get(currentId) ?? null;
|
|
191
|
+
const selectorMatches = parentNode.name === selector.name &&
|
|
192
|
+
(!selector.range ||
|
|
193
|
+
!isValidRange(selector.range) ||
|
|
194
|
+
(parentVersion !== null && satisfiesRange(parentVersion, selector.range)));
|
|
195
|
+
if (selectorMatches) {
|
|
196
|
+
if (chainIndex === 0)
|
|
197
|
+
return true;
|
|
198
|
+
for (const grandParentId of ctx.parentNodeIdsByChildNodeId.get(currentId) ?? []) {
|
|
199
|
+
stack.push({ currentId: grandParentId, chainIndex: chainIndex - 1 });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// Nested npm overrides apply through intermediate transitive dependencies.
|
|
203
|
+
for (const grandParentId of ctx.parentNodeIdsByChildNodeId.get(currentId) ?? []) {
|
|
204
|
+
stack.push({ currentId: grandParentId, chainIndex });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
function collectLegacyAliasRegistryNames(deps) {
|
|
210
|
+
const byPath = new Map();
|
|
211
|
+
const walk = (entries, prefix) => {
|
|
212
|
+
if (!isRecord(entries))
|
|
213
|
+
return;
|
|
214
|
+
for (const [name, meta] of Object.entries(entries)) {
|
|
215
|
+
if (!isRecord(meta))
|
|
216
|
+
continue;
|
|
217
|
+
const packagePath = prefix ? `${prefix}/node_modules/${name}` : `node_modules/${name}`;
|
|
218
|
+
const registryName = npmAliasRegistryName(meta.version);
|
|
219
|
+
if (registryName)
|
|
220
|
+
byPath.set(packagePath, registryName);
|
|
221
|
+
if (meta.dependencies)
|
|
222
|
+
walk(meta.dependencies, packagePath);
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
walk(deps, "");
|
|
226
|
+
return byPath;
|
|
227
|
+
}
|
|
228
|
+
function looksLikeRegistryVersionSpec(spec) {
|
|
229
|
+
const trimmed = spec.trim();
|
|
230
|
+
if (!trimmed)
|
|
231
|
+
return false;
|
|
232
|
+
if (trimmed.startsWith("npm:"))
|
|
233
|
+
return true;
|
|
234
|
+
if (trimmed.includes(":") || trimmed.includes("/"))
|
|
235
|
+
return false;
|
|
236
|
+
return isValidRange(trimmed) || /^[A-Za-z0-9._-]+$/.test(trimmed);
|
|
237
|
+
}
|
|
238
|
+
function isRegistryTarballForPackage(resolvedUrl, manifestName, version) {
|
|
239
|
+
if (!resolvedUrl || !version)
|
|
240
|
+
return false;
|
|
241
|
+
const cleanUrl = resolvedUrl.split(/[?#]/, 1)[0];
|
|
242
|
+
const unscoped = manifestName.startsWith("@")
|
|
243
|
+
? manifestName.slice(manifestName.indexOf("/") + 1)
|
|
244
|
+
: manifestName;
|
|
245
|
+
if (!unscoped)
|
|
246
|
+
return false;
|
|
247
|
+
return cleanUrl.endsWith(`/${manifestName}/-/${unscoped}-${version}.tgz`);
|
|
248
|
+
}
|