cve-lite-cli 1.40.0 → 1.41.1

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 (75) hide show
  1. package/README.md +17 -11
  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 +4 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +11 -25
  12. package/dist/index.js +8 -3
  13. package/dist/output/cyclonedx.js +23 -14
  14. package/dist/output/debug.js +68 -18
  15. package/dist/output/formatters.js +33 -5
  16. package/dist/output/html-reporter.js +55 -5
  17. package/dist/output/multi-folder-html-reporter.js +59 -3
  18. package/dist/output/output-dir.js +193 -7
  19. package/dist/output/override-fix-command.js +5 -7
  20. package/dist/output/printers.js +16 -5
  21. package/dist/output/sarif.js +131 -48
  22. package/dist/output/sbom-dependency-edges.js +16 -10
  23. package/dist/output/sbom-file.js +14 -6
  24. package/dist/output/scan-json.js +21 -3
  25. package/dist/output/spdx.js +61 -23
  26. package/dist/output/spinner.js +2 -1
  27. package/dist/output/write-outputs.js +142 -52
  28. package/dist/overrides/context-builder.js +23 -70
  29. package/dist/overrides/parsing/registry.js +19 -69
  30. package/dist/parsers/bun-lock.js +1 -2
  31. package/dist/parsers/index.js +22 -1
  32. package/dist/parsers/npm-lock-graph.js +39 -1
  33. package/dist/parsers/package-lock.js +25 -5
  34. package/dist/parsers/pnpm-lock.js +3 -2
  35. package/dist/parsers/utils.js +5 -3
  36. package/dist/parsers/yarn-lock-graph.js +36 -17
  37. package/dist/parsers/yarn-lock.js +92 -25
  38. package/dist/remediation/fix-commands.js +101 -45
  39. package/dist/remediation/npm-registry.js +10 -2
  40. package/dist/remediation/npm-transitive-graph.js +30 -72
  41. package/dist/remediation/npm-transitive-resolution.js +24 -77
  42. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  43. package/dist/remediation/parent-upgrade.js +5 -79
  44. package/dist/remediation/registry-parent-ranges.js +21 -0
  45. package/dist/remediation/transitive-chain-resolver.js +3 -3
  46. package/dist/scan/completeness.js +10 -4
  47. package/dist/scan/multi-folder-scan.js +133 -58
  48. package/dist/scan/override-audit.js +6 -4
  49. package/dist/scan/single-scan.js +41 -25
  50. package/dist/scanner.js +263 -58
  51. package/dist/usage/scanner.js +19 -8
  52. package/dist/utils/array.js +11 -3
  53. package/dist/utils/checked-address-policy.js +44 -0
  54. package/dist/utils/debug-bundle.js +118 -0
  55. package/dist/utils/debug-project.js +102 -0
  56. package/dist/utils/debug-redaction.js +117 -0
  57. package/dist/utils/file.js +2 -1
  58. package/dist/utils/fix-runner.js +95 -13
  59. package/dist/utils/import-type-queries.js +322 -0
  60. package/dist/utils/network.js +14 -9
  61. package/dist/utils/npm-lockfile.js +12 -0
  62. package/dist/utils/osv-fetch.js +34 -0
  63. package/dist/utils/package-identity.js +43 -0
  64. package/dist/utils/package-manager-source.js +24 -0
  65. package/dist/utils/purl.js +37 -0
  66. package/dist/utils/registry-config.js +47 -15
  67. package/dist/utils/registry-fetch.js +42 -0
  68. package/dist/utils/shell-quote.js +12 -0
  69. package/dist/utils/string.js +8 -0
  70. package/dist/utils/validate-url.js +1 -1
  71. package/dist/utils/version.js +30 -7
  72. package/dist/utils/versions/osv-range.js +191 -0
  73. package/dist/utils/versions/pep440.js +246 -0
  74. package/dist/utils/versions/scheme.js +10 -0
  75. package/package.json +3 -2
@@ -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);
@@ -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,14 @@ 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,
200
+ signal: init?.signal ?? undefined,
196
201
  };
197
202
  const req = https.request(reqOptions, res => {
198
203
  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,34 @@
1
+ import { FLAG_ALLOW_PRIVATE_OSV_URL, FLAG_OSV_URL } from "../cli/flags.js";
2
+ import { createCheckedAddressPolicy } from "./checked-address-policy.js";
3
+ import { createCertAwareFetch } from "./network.js";
4
+ import { isOfficialOsv } from "./validate-url.js";
5
+ /** Protect only the configured OSV origin; registry and other fetches keep their transport. */
6
+ export function createOsvFetch(osvUrl, allowPrivate, caCertPath) {
7
+ const fallback = caCertPath ? createCertAwareFetch(caCertPath) : fetch;
8
+ if (isOfficialOsv(osvUrl)) {
9
+ return fallback;
10
+ }
11
+ // Parse lazily: validateOptions owns invalid-URL diagnostics before any request.
12
+ const addressPolicy = createCheckedAddressPolicy({
13
+ allowPrivate,
14
+ invalidAddressMessage: `${FLAG_OSV_URL} did not resolve to a valid IP address`,
15
+ privateAddressError: () => new Error(`${FLAG_OSV_URL} resolves to a private/reserved IP at connection time. ` +
16
+ `Use ${FLAG_ALLOW_PRIVATE_OSV_URL} for internal mirrors.`),
17
+ missingFamilyMessage: `${FLAG_OSV_URL} has no address for the requested IP family`,
18
+ });
19
+ const protectedFetch = createCertAwareFetch(caCertPath, addressPolicy.lookup);
20
+ return async (input, init) => {
21
+ const target = new URL(osvUrl);
22
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
23
+ if (url.origin !== target.origin) {
24
+ return fallback(input, init);
25
+ }
26
+ if (url.protocol !== "https:") {
27
+ throw new Error(`${FLAG_OSV_URL} requires https:// scheme`);
28
+ }
29
+ addressPolicy.checkLiteral(url.hostname);
30
+ // The HTTPS transport never follows redirects. It retains the hostname for
31
+ // Host, SNI and certificate validation, and validates DNS for each new socket.
32
+ return protectedFetch(url, init);
33
+ };
34
+ }
@@ -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
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Whether a scan source is an npm lockfile. `npm-shrinkwrap.json` has the same
3
+ * format as `package-lock.json` and npm reads it in preference, so every
4
+ * npm-specific path must accept both.
5
+ */
6
+ export function isNpmLockSource(source) {
7
+ return source === "package-lock" || source === "npm-shrinkwrap";
8
+ }
9
+ /**
10
+ * Which package manager a lockfile source implies, so callers that know the scan
11
+ * source do not each repeat the mapping. Returns null for the package.json fallback,
12
+ * which has no lockfile and therefore no manager.
13
+ */
14
+ export function packageManagerForSource(source) {
15
+ if (isNpmLockSource(source))
16
+ return "npm";
17
+ if (source === "pnpm-lock")
18
+ return "pnpm";
19
+ if (source === "yarn-lock")
20
+ return "yarn";
21
+ if (source === "bun-lock")
22
+ return "bun";
23
+ return null;
24
+ }
@@ -1,3 +1,4 @@
1
+ import { registryPackageName } from "./package-identity.js";
1
2
  /**
2
3
  * Builds a Package URL (purl) for an npm package.
3
4
  *
@@ -8,3 +9,39 @@ export function buildPurl(name, version) {
8
9
  const encodedName = name.startsWith("@") ? `%40${name.slice(1)}` : name;
9
10
  return `pkg:npm/${encodedName}@${version}`;
10
11
  }
12
+ /**
13
+ * Percent-encode a purl version the way the spec requires.
14
+ *
15
+ * Unreserved characters and `:` stay literal. `/` stays literal because the
16
+ * reference encoder treats it as safe. `!` and `+` are reserved, so an epoch
17
+ * `1!2.0` is `1%212.0` and a local label `1.2.3+local` is `1.2.3%2Blocal`.
18
+ */
19
+ function encodePurlVersion(version) {
20
+ return encodeURIComponent(version)
21
+ .replace(/[!'()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)
22
+ .replace(/%3A/g, ":")
23
+ .replace(/%2F/g, "/");
24
+ }
25
+ /**
26
+ * PyPI follows the purl type rule: lowercase, and `_` becomes `-`. Dots stay.
27
+ * That is separate from PEP 503, which also folds dots.
28
+ */
29
+ export function buildEcosystemPurl(ecosystem, name, version) {
30
+ const type = ecosystem.trim().toLowerCase();
31
+ if (type === "npm")
32
+ return buildPurl(name, version);
33
+ if (type === "pypi") {
34
+ const distribution = name.toLowerCase().replace(/_/g, "-");
35
+ return `pkg:pypi/${distribution}@${encodePurlVersion(version)}`;
36
+ }
37
+ return null;
38
+ }
39
+ export function purlForSbom(pkg) {
40
+ if (pkg.ecosystem.trim().toLowerCase() !== "npm")
41
+ return null;
42
+ return buildEcosystemPurl(pkg.ecosystem, registryPackageName(pkg), pkg.version);
43
+ }
44
+ /** Two installation aliases may share a purl but need distinct component refs. */
45
+ export function sbomComponentRef(pkg, purl) {
46
+ return pkg.registryName ? `${purl}#installed-as=${encodeURIComponent(pkg.name)}` : purl;
47
+ }
@@ -92,11 +92,17 @@ function readIfPresent(file) {
92
92
  export function resolveRegistryConfig(args) {
93
93
  const env = args.env ?? process.env;
94
94
  const homeDir = args.homeDir ?? os.homedir();
95
+ const config = args.packageManager ? MANAGER_CONFIG[args.packageManager] : undefined;
95
96
  const envRegistry = env.NPM_CONFIG_REGISTRY || env.npm_config_registry;
96
97
  if (envRegistry) {
97
- return { registry: envRegistry, scopes: {}, sourceFile: "NPM_CONFIG_REGISTRY" };
98
+ const explicit = Boolean(env.NPM_CONFIG_REGISTRY) && (args.platform ?? process.platform) !== "win32";
99
+ return {
100
+ registry: envRegistry,
101
+ scopes: {},
102
+ sourceFile: env.NPM_CONFIG_REGISTRY ? "NPM_CONFIG_REGISTRY" : "npm_config_registry",
103
+ allowPrivate: explicit || isUserRegistry(envRegistry, config, homeDir, args.projectPath),
104
+ };
98
105
  }
99
- const config = args.packageManager ? MANAGER_CONFIG[args.packageManager] : undefined;
100
106
  if (!config)
101
107
  return { registry: NPM_PUBLIC_REGISTRY, scopes: {}, sourceFile: null };
102
108
  for (const dir of [args.projectPath, homeDir]) {
@@ -113,26 +119,43 @@ export function resolveRegistryConfig(args) {
113
119
  registry: parsed.registry || NPM_PUBLIC_REGISTRY,
114
120
  scopes: parsed.scopes,
115
121
  sourceFile: file,
122
+ // A project scanned at home (or a home config linked into the project)
123
+ // must not promote repository-owned settings to user authorization.
124
+ allowPrivate: dir === homeDir && !isInsideProject(file, args.projectPath),
116
125
  };
117
126
  }
118
127
  return { registry: NPM_PUBLIC_REGISTRY, scopes: {}, sourceFile: null };
119
128
  }
120
129
  /**
121
- * Which package manager a lockfile source implies, so callers that know the scan
122
- * source do not each repeat the mapping. Returns null for the package.json fallback,
123
- * which has no lockfile and therefore no manager to read config for.
130
+ * npm and npx export every setting they read, including a project's own `.npmrc`, to
131
+ * child processes as lowercase `npm_config_*` variables. So a lowercase registry
132
+ * variable may be repository-owned, and only earns trust when it is the public
133
+ * registry or the one in the user's own config. Windows environment names ignore
134
+ * case, so there even the uppercase spelling cannot be told apart.
124
135
  */
125
- export function packageManagerForSource(source) {
126
- if (source === "package-lock" || source === "npm-shrinkwrap")
127
- return "npm";
128
- if (source === "pnpm-lock")
129
- return "pnpm";
130
- if (source === "yarn-lock")
131
- return "yarn";
132
- if (source === "bun-lock")
133
- return "bun";
134
- return null;
136
+ function isUserRegistry(registry, config, homeDir, projectPath) {
137
+ const target = normaliseRegistry(registry);
138
+ if (target === normaliseRegistry(NPM_PUBLIC_REGISTRY))
139
+ return true;
140
+ if (!config)
141
+ return false;
142
+ const file = path.join(homeDir, config.file);
143
+ const contents = readIfPresent(file);
144
+ if (contents === null || isInsideProject(file, projectPath))
145
+ return false;
146
+ const home = (config.format === "ini" ? fromIni(contents) : fromYaml(contents)).registry;
147
+ return Boolean(home) && normaliseRegistry(home) === target;
148
+ }
149
+ function normaliseRegistry(registry) {
150
+ try {
151
+ const url = new URL(registry);
152
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
153
+ }
154
+ catch {
155
+ return registry;
156
+ }
135
157
  }
158
+ export { packageManagerForSource } from "./package-manager-source.js";
136
159
  /** The registry a single package resolves through, honouring its scope. */
137
160
  export function registryForPackage(config, packageName) {
138
161
  if (packageName.startsWith("@")) {
@@ -142,3 +165,12 @@ export function registryForPackage(config, packageName) {
142
165
  }
143
166
  return config.registry;
144
167
  }
168
+ function isInsideProject(file, projectPath) {
169
+ try {
170
+ const relative = path.relative(fs.realpathSync(projectPath), fs.realpathSync(file));
171
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
172
+ }
173
+ catch {
174
+ return true;
175
+ } // Uncertain ownership must not authorize private access.
176
+ }