cve-lite-cli 1.39.0 → 1.41.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 (82) hide show
  1. package/README.md +28 -22
  2. package/dist/advisory/local-advisory-source.js +9 -5
  3. package/dist/advisory/local-db.js +91 -13
  4. package/dist/advisory/osv-sync.js +187 -56
  5. package/dist/advisory/staging-directory.js +112 -0
  6. package/dist/cli/advisories-sync.js +16 -2
  7. package/dist/cli/args.js +46 -35
  8. package/dist/cli/config.js +4 -1
  9. package/dist/cli/help.js +5 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +15 -28
  12. package/dist/index.js +8 -3
  13. package/dist/osv/severity.js +1 -1
  14. package/dist/output/cyclonedx.js +24 -15
  15. package/dist/output/debug.js +68 -18
  16. package/dist/output/formatters.js +35 -7
  17. package/dist/output/html-reporter.js +68 -12
  18. package/dist/output/multi-folder-html-reporter.js +71 -11
  19. package/dist/output/output-dir.js +193 -7
  20. package/dist/output/override-findings-html.js +3 -6
  21. package/dist/output/override-findings-terminal.js +7 -12
  22. package/dist/output/override-fix-command.js +13 -0
  23. package/dist/output/printers.js +27 -12
  24. package/dist/output/sarif.js +168 -57
  25. package/dist/output/sbom-dependency-edges.js +16 -10
  26. package/dist/output/sbom-file.js +14 -6
  27. package/dist/output/scan-json.js +46 -3
  28. package/dist/output/spdx.js +61 -23
  29. package/dist/output/spinner.js +2 -1
  30. package/dist/output/write-outputs.js +143 -41
  31. package/dist/overrides/context-builder.js +23 -70
  32. package/dist/overrides/parsing/registry.js +1 -1
  33. package/dist/parsers/bun-lock.js +1 -2
  34. package/dist/parsers/index.js +22 -1
  35. package/dist/parsers/npm-lock-graph.js +39 -1
  36. package/dist/parsers/package-lock.js +25 -5
  37. package/dist/parsers/pnpm-lock.js +26 -12
  38. package/dist/parsers/utils.js +5 -3
  39. package/dist/parsers/yarn-lock-graph.js +5 -2
  40. package/dist/parsers/yarn-lock.js +1 -2
  41. package/dist/remediation/fix-commands.js +140 -50
  42. package/dist/remediation/npm-registry.js +56 -7
  43. package/dist/remediation/npm-transitive-graph.js +30 -72
  44. package/dist/remediation/npm-transitive-resolution.js +35 -107
  45. package/dist/remediation/parent-candidate-resolver.js +65 -0
  46. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  47. package/dist/remediation/parent-upgrade.js +11 -116
  48. package/dist/remediation/registry-parent-ranges.js +21 -0
  49. package/dist/remediation/transitive-chain-resolver.js +3 -3
  50. package/dist/scan/completeness.js +17 -11
  51. package/dist/scan/multi-folder-scan.js +154 -59
  52. package/dist/scan/override-audit.js +11 -1
  53. package/dist/scan/single-scan.js +123 -67
  54. package/dist/scanner.js +288 -66
  55. package/dist/skills/content.js +12 -12
  56. package/dist/usage/scanner.js +19 -8
  57. package/dist/utils/array.js +11 -3
  58. package/dist/utils/contextual-signals.js +1 -1
  59. package/dist/utils/debug-bundle.js +118 -0
  60. package/dist/utils/debug-project.js +102 -0
  61. package/dist/utils/debug-redaction.js +117 -0
  62. package/dist/utils/effective-options.js +55 -0
  63. package/dist/utils/file.js +2 -1
  64. package/dist/utils/finding.js +1 -1
  65. package/dist/utils/fix-runner.js +98 -15
  66. package/dist/utils/import-type-queries.js +322 -0
  67. package/dist/utils/network.js +14 -10
  68. package/dist/utils/npm-lockfile.js +12 -0
  69. package/dist/utils/osv-fetch.js +70 -0
  70. package/dist/utils/package-identity.js +43 -0
  71. package/dist/utils/package-manager-source.js +24 -0
  72. package/dist/utils/purl.js +37 -0
  73. package/dist/utils/registry-config.js +129 -0
  74. package/dist/utils/severity.js +8 -0
  75. package/dist/utils/string.js +8 -0
  76. package/dist/utils/validate-url.js +4 -4
  77. package/dist/utils/version.js +47 -8
  78. package/dist/utils/versions/osv-range.js +191 -0
  79. package/dist/utils/versions/pep440.js +246 -0
  80. package/dist/utils/versions/scheme.js +10 -0
  81. package/dist/utils/vuln.js +75 -0
  82. package/package.json +3 -2
@@ -5,7 +5,7 @@ import { createSpinner } from "../output/spinner.js";
5
5
  import { chalk } from "./chalk.js";
6
6
  import { pluralize } from "./string.js";
7
7
  import { isBreakingUpgrade } from "./version.js";
8
- import { buildTargetCommand } from "../remediation/fix-commands.js";
8
+ import { installPackageSpec } from "./package-identity.js";
9
9
  import { formatParentUpdateChildNote } from "../remediation/parent-update-child-note.js";
10
10
  export async function runInstallCommand(command, args, cwd, debugLog) {
11
11
  const commandLine = [command, ...args].join(" ");
@@ -61,19 +61,101 @@ const EMPTY_UNAPPLIED = {
61
61
  breakingUpgradeCount: 0,
62
62
  noFixCount: 0,
63
63
  };
64
- // Build the command(s) to apply a target. Within-range refresh (parent-update)
65
- // targets carry an explicit, already-workspace-scoped command; direct targets
66
- // are installed by version. A multi-member workspace command is `&&`-joined and
67
- // is split into one spawn per member.
64
+ // Build argv lists for --fix without round-tripping through a shell string.
65
+ // Workspace paths and package tokens are passed as whole argv elements to spawn
66
+ // (no shell), so a directory name containing `&&` cannot become a second executable.
67
+ // Human-facing plan strings still come from buildTargetCommand.
68
68
  function buildApplyCommands(packageManager, target) {
69
- // Use the same workspace-scoped command the report/plan shows, so --fix applies
70
- // fixes to the declaring member (npm install -w, pnpm --filter ...) rather than
71
- // flat at the root. A multi-member command is `&&`-joined; split per spawn.
72
- return buildTargetCommand(target, packageManager)
73
- .split("&&")
74
- .map(part => part.trim())
75
- .filter(Boolean)
76
- .map(part => part.split(/\s+/));
69
+ if (target.kind === "parent-update") {
70
+ return buildParentUpdateApplyArgv(packageManager, target);
71
+ }
72
+ return buildInstallApplyArgv(packageManager, target);
73
+ }
74
+ function buildInstallApplyArgv(packageManager, target) {
75
+ const workspaces = (target.workspaces ?? []).filter(w => w !== ".");
76
+ const pkgArg = installPackageSpec(target);
77
+ const isDev = Boolean(target.isDev);
78
+ if (packageManager === "npm") {
79
+ const args = ["install"];
80
+ if (isDev)
81
+ args.push("-D");
82
+ for (const ws of workspaces) {
83
+ args.push("-w", ws);
84
+ }
85
+ args.push(pkgArg);
86
+ return [["npm", ...args]];
87
+ }
88
+ if (packageManager === "pnpm") {
89
+ const args = [];
90
+ for (const ws of workspaces) {
91
+ args.push("--filter", `./${ws}`);
92
+ }
93
+ args.push("add");
94
+ if (isDev)
95
+ args.push("-D");
96
+ args.push(pkgArg);
97
+ return [["pnpm", ...args]];
98
+ }
99
+ if (packageManager === "yarn") {
100
+ if (workspaces.length === 0) {
101
+ const args = ["add"];
102
+ if (isDev)
103
+ args.push("-D");
104
+ args.push(pkgArg);
105
+ return [["yarn", ...args]];
106
+ }
107
+ return workspaces.map(ws => {
108
+ const args = ["workspace", ws, "add"];
109
+ if (isDev)
110
+ args.push("-D");
111
+ args.push(pkgArg);
112
+ return ["yarn", ...args];
113
+ });
114
+ }
115
+ // bun
116
+ const args = ["add"];
117
+ if (isDev)
118
+ args.push("--dev");
119
+ for (const ws of workspaces) {
120
+ args.push("--filter", ws);
121
+ }
122
+ args.push(pkgArg);
123
+ return [["bun", ...args]];
124
+ }
125
+ function buildParentUpdateApplyArgv(packageManager, target) {
126
+ // Always build from structured fields. Never tokenize target.command: plan
127
+ // strings may be shell-quoted for display, and must not be re-parsed into argv.
128
+ const updatePkg = target.childPackage ?? target.package;
129
+ const workspaces = target.workspaces ?? [];
130
+ const nonRoot = workspaces.filter(w => w !== ".");
131
+ if (packageManager === "npm") {
132
+ const args = ["update"];
133
+ if (nonRoot.length === 1) {
134
+ args.push(`--workspace=${nonRoot[0]}`);
135
+ }
136
+ else if (nonRoot.length > 1) {
137
+ args.push("--workspaces");
138
+ }
139
+ args.push(updatePkg);
140
+ return [["npm", ...args]];
141
+ }
142
+ if (packageManager === "pnpm") {
143
+ if (workspaces.length === 0 || workspaces.length > 1) {
144
+ return [["pnpm", "update", "--recursive", "--no-save", updatePkg]];
145
+ }
146
+ const workspace = workspaces[0];
147
+ if (workspace === ".") {
148
+ return [["pnpm", "update", "--no-save", updatePkg]];
149
+ }
150
+ return [["pnpm", "--filter", `./${workspace}`, "update", "--no-save", updatePkg]];
151
+ }
152
+ if (packageManager === "yarn") {
153
+ if (nonRoot.length === 0) {
154
+ return [["yarn", "upgrade", updatePkg]];
155
+ }
156
+ return nonRoot.map(ws => ["yarn", "workspace", ws, "upgrade", updatePkg]);
157
+ }
158
+ return [["bun", "update", updatePkg]];
77
159
  }
78
160
  export function writeFixResultJson(json, projectPath) {
79
161
  const outPath = path.join(projectPath, "cve-lite-fix-result.json");
@@ -111,8 +193,9 @@ export async function applyFixesIfRequested(params) {
111
193
  const spinner = createSpinner(`Applying safe package fixes with ${commandLabel}... 0/${total}`, params.options);
112
194
  const fixHint = `\nHint: Check that \`${params.plan.packageManager}\` is available and you have write access to node_modules.\nIf running in CI, ensure the install step has already run before cve-lite --fix.`;
113
195
  // parent-update is keyed per child, so two children behind one parent produce
114
- // two targets with the same `npm update <parent>` command. Spawn each command
115
- // once; the displayed plan already dedupes the same way.
196
+ // two targets. npm update names the child, so those commands differ. Two
197
+ // parents that refresh the same child can still share `npm update <child>`.
198
+ // Spawn each command once; the displayed plan already dedupes the same way.
116
199
  const seenCommands = new Set();
117
200
  for (let i = 0; i < applyTargets.length; i++) {
118
201
  const target = applyTargets[i];
@@ -0,0 +1,322 @@
1
+ // Strings and regex literals are single tokens so text such as "type T ="
2
+ // cannot put a later runtime import into a type declaration.
3
+ const TOKENS = /'(?:\\[\s\S]|[^'\\])*'|"(?:\\[\s\S]|[^"\\])*"|`(?:\\[\s\S]|[^`\\])*`|\/(?![/*])(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\[\n])+\/[a-z]*|[\w$]+|=>|[^\s]/g;
4
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
5
+ const TYPE_CONTINUATIONS = new Set(["=", "=>", "|", "&", ".", ",", "?", ":", "extends", "keyof", "typeof", "readonly", "infer"]);
6
+ const TYPE_SUFFIXES = new Set(["|", "&", ".", "[", "<", "extends", "?", ":"]);
7
+ const EXPRESSION_CONTINUATIONS = new Set([
8
+ ...TYPE_CONTINUATIONS, "+", "-", "*", "/", "%", "^", "!", "~", "<", ">",
9
+ "as", "satisfies", "await", "yield", "new", "in", "instanceof", "void", "delete",
10
+ ]);
11
+ const OPEN_TO_CLOSE = new Map([["(", ")"], ["[", "]"], ["{", "}"], ["<", ">"]]);
12
+ const TYPE_TERMINATORS = new Set([";", "=", ",", ")", "}"]);
13
+ const INTERFACE_HEADER_END = new Set(["{", ";", "="]);
14
+ const VARIABLE_KEYWORDS = new Set(["const", "let", "var"]);
15
+ const MEMBER_MODIFIERS = new Set(["public", "private", "protected", "static", "readonly", "abstract", "declare", "override", "accessor", "async", "get", "set"]);
16
+ const MEMBER_SUFFIXES = new Set(["?", "!", ":", "=", "(", "<", ";", "}"]);
17
+ const MEMBER_STARTS = new Set(["{", "}", ",", ";"]);
18
+ function startsNewStatement(tokens, index, start, source, continuations = TYPE_CONTINUATIONS) {
19
+ return index > start && /[\r\n]/.test(source.slice(tokens[index - 1].end, tokens[index].start))
20
+ && !continuations.has(tokens[index - 1].text) && !TYPE_SUFFIXES.has(tokens[index].text);
21
+ }
22
+ function syntaxPairs(tokens) {
23
+ const pairs = new Map();
24
+ const stack = [];
25
+ for (let i = 0; i < tokens.length; i++) {
26
+ const text = tokens[i].text;
27
+ // Angle brackets are paired only in known type spans: `<` can also be a
28
+ // comparison in a runtime initializer.
29
+ if (text !== "<" && OPEN_TO_CLOSE.has(text)) {
30
+ stack.push(i);
31
+ }
32
+ else if (text === OPEN_TO_CLOSE.get(tokens[stack[stack.length - 1]]?.text)) {
33
+ const open = stack.pop();
34
+ pairs.set(open, i);
35
+ }
36
+ }
37
+ return pairs;
38
+ }
39
+ function typeParametersEnd(tokens, start) {
40
+ if (tokens[start]?.text !== "<") {
41
+ return start;
42
+ }
43
+ let depth = 0;
44
+ for (let i = start; i < tokens.length; i++) {
45
+ if (tokens[i].text === "<") {
46
+ depth++;
47
+ }
48
+ else if (tokens[i].text === ">" && --depth === 0) {
49
+ return i + 1;
50
+ }
51
+ }
52
+ return start;
53
+ }
54
+ function addTypeQueries(tokens, start, end, offsets) {
55
+ for (let i = start; i < end; i++) {
56
+ if (tokens[i].text === "import" && tokens[i + 1]?.text === "(") {
57
+ offsets.add(tokens[i].start);
58
+ }
59
+ }
60
+ }
61
+ function memberNameEnd(tokens, start, pairs) {
62
+ let next = start;
63
+ while (MEMBER_MODIFIERS.has(tokens[next]?.text) && !MEMBER_SUFFIXES.has(tokens[next + 1]?.text)) {
64
+ next++;
65
+ }
66
+ if (tokens[next]?.text === "#") {
67
+ next++;
68
+ }
69
+ next = tokens[next]?.text === "[" ? (pairs.get(next) ?? next) + 1 : next + 1;
70
+ if (tokens[next]?.text === "?" || tokens[next]?.text === "!") {
71
+ next++;
72
+ }
73
+ return next;
74
+ }
75
+ function returnTypeEnd(tokens, start, source, pairs, arrow) {
76
+ for (let i = start; i < tokens.length; i++) {
77
+ const text = tokens[i].text;
78
+ if (TYPE_TERMINATORS.has(text) || (arrow && text === "=>")) {
79
+ return i;
80
+ }
81
+ if (startsNewStatement(tokens, i, start, source)) {
82
+ return i;
83
+ }
84
+ // An object type starts a type or follows a type operator. A subsequent
85
+ // brace opens the executable function body and must never be erased.
86
+ if (text === "{" && i > start && !TYPE_CONTINUATIONS.has(tokens[i - 1].text)) {
87
+ return i;
88
+ }
89
+ if (pairs.has(i)) {
90
+ i = pairs.get(i);
91
+ }
92
+ else if (text === "<") {
93
+ i = Math.max(i, typeParametersEnd(tokens, i) - 1);
94
+ }
95
+ }
96
+ return tokens.length;
97
+ }
98
+ function signatureTypes(tokens, open, source, pairs, offsets, arrow = false) {
99
+ const close = pairs.get(open);
100
+ if (close === undefined) {
101
+ return open + 1;
102
+ }
103
+ for (let i = open + 1; i < close; i++) {
104
+ while (tokens[i]?.text === "." || MEMBER_MODIFIERS.has(tokens[i]?.text)) {
105
+ i++;
106
+ }
107
+ i = pairs.has(i) ? pairs.get(i) + 1 : i + 1;
108
+ if (tokens[i]?.text === "?") {
109
+ i++;
110
+ }
111
+ if (tokens[i]?.text === ":") {
112
+ const end = typeEnd(tokens, i + 1, source);
113
+ addTypeQueries(tokens, i + 1, end, offsets);
114
+ i = end;
115
+ }
116
+ // Everything after `=` is an executable default, including object values
117
+ // containing colons. Resume only at the next parameter, outside groups.
118
+ while (i < close && tokens[i].text !== ",") {
119
+ i = (pairs.get(i) ?? i) + 1;
120
+ }
121
+ }
122
+ if (tokens[close + 1]?.text !== ":") {
123
+ return close + 1;
124
+ }
125
+ const start = close + 2;
126
+ const end = returnTypeEnd(tokens, start, source, pairs, arrow);
127
+ addTypeQueries(tokens, start, end, offsets);
128
+ return end;
129
+ }
130
+ function classTypes(tokens, start, source, pairs, offsets) {
131
+ let body = start + 1;
132
+ if (IDENTIFIER.test(tokens[body]?.text ?? "") && tokens[body].text !== "extends") {
133
+ body++;
134
+ }
135
+ const genericEnd = typeParametersEnd(tokens, body);
136
+ addTypeQueries(tokens, body, genericEnd, offsets);
137
+ body = genericEnd;
138
+ while (body < tokens.length && tokens[body].text !== "{") {
139
+ const argumentsEnd = typeParametersEnd(tokens, body);
140
+ if (argumentsEnd > body) {
141
+ addTypeQueries(tokens, body, argumentsEnd, offsets);
142
+ body = argumentsEnd;
143
+ }
144
+ else {
145
+ body = (pairs.get(body) ?? body) + 1;
146
+ }
147
+ }
148
+ const close = pairs.get(body);
149
+ if (close === undefined) {
150
+ return;
151
+ }
152
+ let memberStart = body + 1;
153
+ for (let i = memberStart; i < close; i++) {
154
+ const text = tokens[i].text;
155
+ if (text === ";") {
156
+ memberStart = i + 1;
157
+ }
158
+ else if (startsNewStatement(tokens, i, memberStart, source, EXPRESSION_CONTINUATIONS)) {
159
+ memberStart = i;
160
+ }
161
+ const nameEnd = memberNameEnd(tokens, memberStart, pairs);
162
+ if (text === ":" && nameEnd === i) {
163
+ const end = typeEnd(tokens, i + 1, source);
164
+ addTypeQueries(tokens, i + 1, end, offsets);
165
+ i = end - 1;
166
+ if (tokens[end]?.text !== "=") {
167
+ memberStart = end;
168
+ }
169
+ }
170
+ else if (text === "(" && typeParametersEnd(tokens, nameEnd) === i) {
171
+ addTypeQueries(tokens, nameEnd, i, offsets);
172
+ const end = signatureTypes(tokens, i, source, pairs, offsets);
173
+ i = tokens[end]?.text === "{" ? (pairs.get(end) ?? end) : end;
174
+ memberStart = i + 1;
175
+ }
176
+ else if (pairs.has(i)) {
177
+ const staticBlock = text === "{" && i === memberStart + 1 && tokens[memberStart].text === "static";
178
+ i = pairs.get(i);
179
+ if (staticBlock) {
180
+ memberStart = i + 1;
181
+ }
182
+ }
183
+ }
184
+ }
185
+ function typeEnd(tokens, start, source, interfaceBody = false) {
186
+ const closers = [];
187
+ for (let i = start; i < tokens.length; i++) {
188
+ const token = tokens[i];
189
+ if (closers.length === 0) {
190
+ if (TYPE_TERMINATORS.has(token.text)) {
191
+ return i;
192
+ }
193
+ // Semicolons are optional. A fresh statement after a complete type must
194
+ // not be swallowed, but multiline unions and other continuations must.
195
+ if (startsNewStatement(tokens, i, start, source)) {
196
+ return i;
197
+ }
198
+ }
199
+ const closer = OPEN_TO_CLOSE.get(token.text);
200
+ if (closer) {
201
+ closers.push(closer);
202
+ }
203
+ else if (token.text === closers[closers.length - 1]) {
204
+ closers.pop();
205
+ if (interfaceBody && closers.length === 0) {
206
+ return i + 1;
207
+ }
208
+ }
209
+ }
210
+ return tokens.length;
211
+ }
212
+ /** Locate import() queries in type declarations without erasing runtime calls. */
213
+ export function importTypeQueryOffsets(source) {
214
+ const tokens = [...source.matchAll(TOKENS)].map((match) => ({
215
+ text: match[0], start: match.index, end: match.index + match[0].length,
216
+ }));
217
+ const offsets = new Set();
218
+ for (let i = 0; i < tokens.length; i++) {
219
+ const token = tokens[i];
220
+ let start;
221
+ let queryStart;
222
+ let interfaceBody = false;
223
+ if (token.text === "type" && IDENTIFIER.test(tokens[i + 1]?.text ?? "") && tokens[i - 1]?.text !== ".") {
224
+ let next = i + 2;
225
+ if (tokens[next]?.text === "<") {
226
+ let depth = 0;
227
+ do {
228
+ if (tokens[next].text === "<") {
229
+ depth++;
230
+ }
231
+ else if (tokens[next].text === ">") {
232
+ depth--;
233
+ }
234
+ next++;
235
+ } while (next < tokens.length && depth > 0);
236
+ }
237
+ if (tokens[next]?.text === "=") {
238
+ start = next + 1;
239
+ queryStart = i + 2;
240
+ }
241
+ }
242
+ else if (token.text === "interface" && IDENTIFIER.test(tokens[i + 1]?.text ?? "")) {
243
+ let next = i + 2;
244
+ while (next < tokens.length && !INTERFACE_HEADER_END.has(tokens[next].text)) {
245
+ next++;
246
+ }
247
+ if (tokens[next]?.text === "{") {
248
+ start = next;
249
+ queryStart = i + 2;
250
+ interfaceBody = true;
251
+ }
252
+ }
253
+ else if (VARIABLE_KEYWORDS.has(token.text)
254
+ && IDENTIFIER.test(tokens[i + 1]?.text ?? "") && tokens[i + 2]?.text === ":") {
255
+ start = i + 3;
256
+ }
257
+ if (start === undefined) {
258
+ continue;
259
+ }
260
+ const end = typeEnd(tokens, start, source, interfaceBody);
261
+ addTypeQueries(tokens, queryStart ?? start, end, offsets);
262
+ i = end - 1;
263
+ }
264
+ const pairs = syntaxPairs(tokens);
265
+ for (let i = 0; i < tokens.length; i++) {
266
+ const text = tokens[i].text;
267
+ if (text === "function" && tokens[i - 1]?.text !== ".") {
268
+ let next = i + 1;
269
+ if (tokens[next]?.text === "*") {
270
+ next++;
271
+ }
272
+ if (IDENTIFIER.test(tokens[next]?.text ?? "")) {
273
+ next++;
274
+ }
275
+ const open = typeParametersEnd(tokens, next);
276
+ if (tokens[open]?.text === "(") {
277
+ addTypeQueries(tokens, next, open, offsets);
278
+ signatureTypes(tokens, open, source, pairs, offsets);
279
+ }
280
+ }
281
+ else if (text === "class" && tokens[i - 1]?.text !== "."
282
+ && (IDENTIFIER.test(tokens[i + 1]?.text ?? "") || tokens[i + 1]?.text === "{")) {
283
+ classTypes(tokens, i, source, pairs, offsets);
284
+ }
285
+ else if (IDENTIFIER.test(text) && MEMBER_STARTS.has(tokens[i - 1]?.text)) {
286
+ const nameEnd = memberNameEnd(tokens, i, pairs);
287
+ const open = typeParametersEnd(tokens, nameEnd);
288
+ const close = pairs.get(open);
289
+ if (tokens[open]?.text === "(" && close !== undefined) {
290
+ const end = tokens[close + 1]?.text === ":"
291
+ ? returnTypeEnd(tokens, close + 2, source, pairs, false) : close + 1;
292
+ if (tokens[end]?.text === "{") {
293
+ addTypeQueries(tokens, nameEnd, open, offsets);
294
+ signatureTypes(tokens, open, source, pairs, offsets);
295
+ }
296
+ }
297
+ }
298
+ else if (text === "(" || text === "<") {
299
+ const previous = tokens[i - 1]?.text;
300
+ if (previous && ((IDENTIFIER.test(previous) && previous !== "async")
301
+ || previous === ")" || previous === "]" || previous === ">"
302
+ || previous === "async" && tokens[i - 2]?.text === ".")) {
303
+ continue;
304
+ }
305
+ const open = text === "<" ? typeParametersEnd(tokens, i) : i;
306
+ const close = pairs.get(open);
307
+ if (tokens[open]?.text !== "(" || close === undefined) {
308
+ continue;
309
+ }
310
+ const end = tokens[close + 1]?.text === ":"
311
+ ? returnTypeEnd(tokens, close + 2, source, pairs, true) : close + 1;
312
+ // In `flag ? async() : (x = import('pkg')) => x`, the colon belongs
313
+ // to a conditional expression. A default initializer is not a type.
314
+ const hasInitializer = tokens.slice(close + 2, end).some(token => token.text === "=");
315
+ if (tokens[end]?.text === "=>" && !hasInitializer) {
316
+ addTypeQueries(tokens, i, open, offsets);
317
+ signatureTypes(tokens, open, source, pairs, offsets, true);
318
+ }
319
+ }
320
+ }
321
+ return offsets;
322
+ }
@@ -1,6 +1,7 @@
1
1
  import https from "node:https";
2
2
  import fs from "node:fs";
3
3
  import { rootCertificates } from "node:tls";
4
+ import { stripIpv6Brackets } from "./validate-url.js";
4
5
  export function extractErrorMessage(error) {
5
6
  if (!(error instanceof Error))
6
7
  return String(error);
@@ -11,7 +12,7 @@ export function extractErrorMessage(error) {
11
12
  }
12
13
  export function sslCertificateErrorHint() {
13
14
  return [
14
- "Hint: SSL certificate error — your network may be using a corporate proxy that intercepts HTTPS traffic.",
15
+ "Hint: SSL certificate error. Your network may be using a corporate proxy that intercepts HTTPS traffic.",
15
16
  "Fix (recommended): save your corporate CA certificate path once:",
16
17
  " cve-lite config set ca-cert /path/to/corporate-ca.crt",
17
18
  "Or pass it per-invocation:",
@@ -69,6 +70,7 @@ const SSL_ERROR_MESSAGE_FRAGMENTS = [
69
70
  "self-signed certificate",
70
71
  "certificate chain",
71
72
  "certificate has expired",
73
+ "unable to get local issuer certificate",
72
74
  "unable to verify the first certificate",
73
75
  ];
74
76
  function finalErrorCause(message) {
@@ -152,21 +154,22 @@ export function getNetworkErrorHint(error, errorMessage) {
152
154
  return serverAdvisoryRequestHint();
153
155
  if (isLikelyBlockedAdvisoryRequestError(errorMessage))
154
156
  return blockedAdvisoryRequestHint();
155
- // Local read/parse failures are stamped with this prefix by readInput() in
156
- // src/parsers/index.ts. They are not network failures, so no CA hint.
157
- if (errorMessage.startsWith("Failed to read "))
158
- return [];
159
- return fetchErrorCaCertHint();
157
+ // The generic CA hint is useful for an unclassified fetch failure, but must
158
+ // not be attached to local validation, parsing, or filesystem errors.
159
+ if (/\bosv (?:api|batch|dump)\b/i.test(errorMessage) || errorMessage.toLowerCase().includes("fetch failed")) {
160
+ return fetchErrorCaCertHint();
161
+ }
162
+ return [];
160
163
  }
161
- export function createCertAwareFetch(caCertPath) {
164
+ export function createCertAwareFetch(caCertPath, lookup) {
162
165
  // Lazily create the agent on first use so that callers can be wired up before
163
166
  // the cert path is validated. validateOptions() in index.ts catches invalid
164
167
  // paths before any actual request is made.
165
168
  let agent;
166
169
  function getAgent() {
167
170
  if (!agent) {
168
- const ca = fs.readFileSync(caCertPath);
169
- agent = new https.Agent({ ca: [...rootCertificates, ca] });
171
+ const ca = caCertPath ? [...rootCertificates, fs.readFileSync(caCertPath)] : undefined;
172
+ agent = new https.Agent({ ca });
170
173
  }
171
174
  return agent;
172
175
  }
@@ -187,12 +190,13 @@ export function createCertAwareFetch(caCertPath) {
187
190
  ? Object.fromEntries(new Headers(rawHeaders).entries())
188
191
  : {};
189
192
  const reqOptions = {
190
- hostname: parsed.hostname,
193
+ hostname: stripIpv6Brackets(parsed.hostname),
191
194
  port: parsed.port ? parseInt(parsed.port, 10) : 443,
192
195
  path: parsed.pathname + parsed.search,
193
196
  method,
194
197
  headers,
195
198
  agent: getAgent(),
199
+ lookup,
196
200
  };
197
201
  const req = https.request(reqOptions, res => {
198
202
  const chunks = [];
@@ -0,0 +1,12 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { NPM_LOCKFILE_NAMES } from "../constants.js";
4
+ /** npm ignores package-lock.json whenever npm-shrinkwrap.json is present. */
5
+ export function findNpmLockfile(projectPath) {
6
+ for (const name of NPM_LOCKFILE_NAMES) {
7
+ const filePath = join(projectPath, name);
8
+ if (existsSync(filePath))
9
+ return filePath;
10
+ }
11
+ return null;
12
+ }
@@ -0,0 +1,70 @@
1
+ import dns from "node:dns";
2
+ import { FLAG_ALLOW_PRIVATE_OSV_URL, FLAG_OSV_URL } from "../cli/flags.js";
3
+ import { isIP } from "node:net";
4
+ import { createCertAwareFetch } from "./network.js";
5
+ import { isOfficialOsv, isPrivateOrReservedIp, stripIpv6Brackets } from "./validate-url.js";
6
+ function rejectPrivateAddresses(addresses, allowPrivate) {
7
+ if (addresses.length === 0 || addresses.some(address => !isIP(address.address))) {
8
+ throw new Error(`${FLAG_OSV_URL} did not resolve to a valid IP address`);
9
+ }
10
+ if (!allowPrivate && addresses.some(address => isPrivateOrReservedIp(address.address))) {
11
+ throw new Error(`${FLAG_OSV_URL} resolves to a private/reserved IP at connection time. ` +
12
+ `Use ${FLAG_ALLOW_PRIVATE_OSV_URL} for internal mirrors.`);
13
+ }
14
+ }
15
+ /** Return only the addresses that were checked, without another resolver call. */
16
+ function createOsvLookup(allowPrivate) {
17
+ return (hostname, options, callback) => {
18
+ dns.lookup(hostname, { all: true }, (error, addresses) => {
19
+ if (error) {
20
+ callback(error, "", 0);
21
+ return;
22
+ }
23
+ try {
24
+ rejectPrivateAddresses(addresses, allowPrivate);
25
+ const family = options.family;
26
+ const candidates = family ? addresses.filter(address => address.family === family) : addresses;
27
+ if (candidates.length === 0) {
28
+ throw new Error(`${FLAG_OSV_URL} has no address for the requested IP family`);
29
+ }
30
+ if (options.all) {
31
+ callback(null, candidates);
32
+ }
33
+ else {
34
+ callback(null, candidates[0].address, candidates[0].family);
35
+ }
36
+ }
37
+ catch (failure) {
38
+ callback(failure, "", 0);
39
+ }
40
+ });
41
+ };
42
+ }
43
+ /** Protect only the configured OSV origin; registry and other fetches keep their transport. */
44
+ export function createOsvFetch(osvUrl, allowPrivate, caCertPath) {
45
+ const fallback = caCertPath ? createCertAwareFetch(caCertPath) : fetch;
46
+ if (isOfficialOsv(osvUrl)) {
47
+ return fallback;
48
+ }
49
+ // Parse lazily: validateOptions owns invalid-URL diagnostics before any request.
50
+ const protectedFetch = createCertAwareFetch(caCertPath, createOsvLookup(allowPrivate));
51
+ return async (input, init) => {
52
+ const target = new URL(osvUrl);
53
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
54
+ if (url.origin !== target.origin) {
55
+ return fallback(input, init);
56
+ }
57
+ if (url.protocol !== "https:") {
58
+ throw new Error(`${FLAG_OSV_URL} requires https:// scheme`);
59
+ }
60
+ // Node bypasses lookup callbacks for literals, so enforce the same policy here.
61
+ const hostname = stripIpv6Brackets(url.hostname);
62
+ const family = isIP(hostname);
63
+ if (family) {
64
+ rejectPrivateAddresses([{ address: hostname, family }], allowPrivate);
65
+ }
66
+ // The HTTPS transport never follows redirects. It retains the hostname for
67
+ // Host, SNI and certificate validation, and validates DNS for each new socket.
68
+ return protectedFetch(input, init);
69
+ };
70
+ }
@@ -0,0 +1,43 @@
1
+ import { parseExactManifestVersion } from "./version.js";
2
+ const NPM_ALIAS_PROTOCOL = "npm:";
3
+ /** Installation names identify graph slots; registry names identify advisories. */
4
+ export function registryPackageName(pkg) {
5
+ return pkg.registryName ?? pkg.name;
6
+ }
7
+ export function registryPackage(pkg) {
8
+ return pkg.registryName ? { ...pkg, name: pkg.registryName } : pkg;
9
+ }
10
+ export function packageInstanceKey(pkg) {
11
+ return `${packageNameKey(pkg)}@${pkg.version}`;
12
+ }
13
+ export function packageNameKey(pkg) {
14
+ return pkg.registryName ? `${pkg.name}\u0000${pkg.registryName}` : pkg.name;
15
+ }
16
+ export function npmAliasRegistryName(value) {
17
+ if (typeof value !== "string" || !value.startsWith(NPM_ALIAS_PROTOCOL)) {
18
+ return null;
19
+ }
20
+ const target = value.slice(NPM_ALIAS_PROTOCOL.length);
21
+ const separator = target.lastIndexOf("@");
22
+ return separator > 0 ? target.slice(0, separator) : target;
23
+ }
24
+ /** Keep an npm alias when installing a newer version of its registry package. */
25
+ export function installPackageSpec(target) {
26
+ const version = target.registryName ? `${NPM_ALIAS_PROTOCOL}${target.registryName}@${target.targetVersion}` : target.targetVersion;
27
+ return `${target.package}@${version}`;
28
+ }
29
+ /** npm lockfile v1 stores an alias's resolved name and version in `version`. */
30
+ export function parseNpmAliasVersion(value) {
31
+ if (typeof value !== "string" || !value.startsWith(NPM_ALIAS_PROTOCOL)) {
32
+ return null;
33
+ }
34
+ const separator = value.lastIndexOf("@");
35
+ if (separator <= NPM_ALIAS_PROTOCOL.length) {
36
+ return null;
37
+ }
38
+ const version = parseExactManifestVersion(value.slice(separator + 1));
39
+ if (!version) {
40
+ return null;
41
+ }
42
+ return { registryName: value.slice(NPM_ALIAS_PROTOCOL.length, separator), version };
43
+ }