@shieldaai/security-watch 1.2.1 → 1.4.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 (47) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +69 -42
  4. package/SECURITY.md +4 -1
  5. package/dist/check.d.ts +193 -0
  6. package/dist/check.js +1000 -0
  7. package/dist/cli.js +301 -6
  8. package/dist/config.d.ts +22 -0
  9. package/dist/config.js +32 -0
  10. package/dist/cve-now.js +2 -0
  11. package/dist/delivery.js +30 -0
  12. package/dist/engine.d.ts +25 -0
  13. package/dist/engine.js +64 -4
  14. package/dist/index.d.ts +8 -1
  15. package/dist/index.js +3 -0
  16. package/dist/inventory.d.ts +2 -1
  17. package/dist/inventory.js +2 -3
  18. package/dist/manifests.d.ts +7 -0
  19. package/dist/manifests.js +16 -0
  20. package/dist/mcp-server.d.ts +256 -0
  21. package/dist/mcp-server.js +755 -0
  22. package/dist/mitigations.d.ts +137 -0
  23. package/dist/mitigations.js +426 -0
  24. package/dist/rehearsal.d.ts +25 -0
  25. package/dist/rehearsal.js +2 -0
  26. package/dist/sbom.d.ts +12 -1
  27. package/dist/sbom.js +37 -7
  28. package/dist/shield-candidates.d.ts +97 -0
  29. package/dist/shield-candidates.js +251 -0
  30. package/dist/shield-inputs.d.ts +49 -0
  31. package/dist/shield-inputs.js +297 -0
  32. package/dist/shirudo-sboms.d.ts +62 -0
  33. package/dist/shirudo-sboms.js +598 -0
  34. package/dist/sources.d.ts +2 -0
  35. package/dist/sources.js +14 -0
  36. package/dist/store.js +6 -4
  37. package/dist/types.d.ts +31 -0
  38. package/dist/vex.d.ts +62 -0
  39. package/dist/vex.js +246 -0
  40. package/docs/agents.md +139 -0
  41. package/docs/configuration.md +20 -1
  42. package/docs/mitigations.md +139 -0
  43. package/docs/offline-advisory-preview.md +2 -2
  44. package/docs/sbom.md +4 -4
  45. package/docs/shirudo.md +113 -0
  46. package/npm-shrinkwrap.json +237 -0
  47. package/package.json +10 -5
package/dist/check.js ADDED
@@ -0,0 +1,1000 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { coerce, gt, major, minor, valid } from 'semver';
4
+ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
7
+ import { parseConfig } from './config.js';
8
+ import { runScan } from './engine.js';
9
+ import { normalizeEcosystem, normalizePackageName, exactLibraryVersion, ECOSYSTEMS } from './ecosystems.js';
10
+ import { safeHttp } from './http.js';
11
+ import { systemFromSbom } from './inventory.js';
12
+ import { generateSbom, isDependencyFilePath } from './manifests.js';
13
+ import { importCycloneDxValue, importSbom } from './sbom.js';
14
+ import { osvEvidence } from './sources.js';
15
+ import { Store } from './store.js';
16
+ import { cleanText } from './util.js';
17
+ /**
18
+ * One-shot checks for a project, a package, an advisory or a dependency change, for people and AI
19
+ * agents who need an answer now rather than an alert later. They run the monitor's own engine on an
20
+ * in-memory database, with OSV and the CISA known-exploited catalog (and EPSS when asked), so a
21
+ * check and the monitor agree. Nothing is stored and nothing is sent anywhere but those sources:
22
+ * OSV receives package names and versions, never file contents.
23
+ */
24
+ const OSV = 'https://api.osv.dev/v1';
25
+ const SEVERITY_ORDER = ['unknown', 'low', 'medium', 'high', 'critical'];
26
+ const MAX_GIT_FILES = 2_000;
27
+ const MAX_GIT_BYTES = 20 * 1024 * 1024;
28
+ const MAX_GIT_TOTAL = 200 * 1024 * 1024;
29
+ const ADVISORY_ID = /^[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9.:_]+)+$/;
30
+ /** The reader's warnings that mean a file's packages are missing, rather than notes about them. */
31
+ export const isUnreadableWarning = (warning) => UNREADABLE.test(warning) || UNREADABLE_LINK.test(warning);
32
+ const UNREADABLE_LINK = /: reached through a link that leads outside the project; skipped\.$/;
33
+ const UNREADABLE = /: (?:folder could not be read|could not be read \(.*\)|larger than 20 MiB); skipped\.$/;
34
+ const EMPTY_PROJECT = /no supported dependency files|no dependency files|found no/i;
35
+ function digestOf(value) {
36
+ return `sha256:${createHash('sha256').update(JSON.stringify(value)).digest('hex')}`;
37
+ }
38
+ function projectTarget(options) {
39
+ if (options.sbom) {
40
+ const path = resolve(options.sbom);
41
+ const imported = importSbom(path);
42
+ const loaded = systemFromSbom(path, basename(path), basename(path), imported);
43
+ return {
44
+ kind: 'sbom',
45
+ label: basename(path),
46
+ system: loaded.system,
47
+ files: [],
48
+ ecosystems: [...new Set(imported.components.map((component) => component.ecosystem))].sort(),
49
+ packages: imported.components.length,
50
+ unversioned: imported.components.filter((component) => !component.version).length,
51
+ unreadable: [],
52
+ notices: [...loaded.warnings, ...loaded.notices],
53
+ locations: new Map(),
54
+ };
55
+ }
56
+ const project = resolve(options.project ?? '.');
57
+ let generated;
58
+ try {
59
+ generated = generateSbom({ project, ...(options.production ? { production: true } : {}) });
60
+ }
61
+ catch (error) {
62
+ if (error instanceof Error && EMPTY_PROJECT.test(error.message))
63
+ return emptyTarget(project);
64
+ throw error;
65
+ }
66
+ const locations = new Map();
67
+ for (const component of (generated.bom.components ?? []))
68
+ if (component.purl)
69
+ locations.set(component.purl, (component.evidence?.occurrences ?? []).flatMap((item) => (item.location ? [item.location] : [])));
70
+ const imported = importCycloneDxValue(generated.bom, digestOf(generated.bom));
71
+ const loaded = systemFromSbom(project, basename(project), basename(project), imported);
72
+ return {
73
+ kind: 'project',
74
+ label: project,
75
+ system: loaded.system,
76
+ files: generated.files,
77
+ ecosystems: generated.ecosystems,
78
+ packages: generated.packages,
79
+ unversioned: generated.unversioned,
80
+ unreadable: generated.warnings.filter((warning) => UNREADABLE.test(warning)),
81
+ notices: [
82
+ ...generated.warnings.filter((warning) => !UNREADABLE.test(warning)),
83
+ ...loaded.warnings,
84
+ ...loaded.notices,
85
+ ],
86
+ locations,
87
+ };
88
+ }
89
+ function emptyTarget(label) {
90
+ return {
91
+ kind: 'project',
92
+ label,
93
+ system: blankSystem(basename(label) || 'project', []),
94
+ files: [],
95
+ ecosystems: [],
96
+ packages: 0,
97
+ unversioned: 0,
98
+ unreadable: [],
99
+ notices: [],
100
+ locations: new Map(),
101
+ };
102
+ }
103
+ function blankSystem(name, components) {
104
+ return {
105
+ id: 'check',
106
+ name,
107
+ environment: 'unknown',
108
+ exposure: 'unknown',
109
+ criticality: 'unknown',
110
+ updated_at: new Date().toISOString(),
111
+ components,
112
+ products: [],
113
+ keywords: [],
114
+ };
115
+ }
116
+ /** A GET cache for the sources' static files (KEV, EPSS, OSV records), shared by checks in one session. */
117
+ export function cachingHttp(inner = safeHttp, ttlMs = 15 * 60_000) {
118
+ const cache = new Map();
119
+ return (url, options = {}) => {
120
+ if ((options.method ?? 'GET') !== 'GET')
121
+ return inner(url, options);
122
+ const now = Date.now();
123
+ const hit = cache.get(url);
124
+ if (hit && now - hit.at < ttlMs)
125
+ return hit.result;
126
+ const { signal: _signal, ...rest } = options;
127
+ const result = inner(url, rest).then((response) => {
128
+ if (response.status !== 200)
129
+ cache.delete(url);
130
+ return response;
131
+ }, (error) => {
132
+ cache.delete(url);
133
+ throw error;
134
+ });
135
+ cache.set(url, { at: now, result });
136
+ if (cache.size > 2_000)
137
+ cache.delete(cache.keys().next().value);
138
+ return result;
139
+ };
140
+ }
141
+ async function run(target, options) {
142
+ const now = options.now ?? Date.now();
143
+ const kev = options.kev ?? true;
144
+ const epss = options.epss ?? false;
145
+ const sources = ['osv', ...(kev ? ['kev'] : []), ...(epss ? ['epss'] : [])];
146
+ const report = {
147
+ kind: target.kind,
148
+ checked_at: new Date(now).toISOString(),
149
+ target: target.label,
150
+ packages: target.packages,
151
+ unversioned: target.unversioned,
152
+ files: target.files,
153
+ ecosystems: target.ecosystems,
154
+ findings: [],
155
+ sources,
156
+ // A file that could not be read hides its packages: no answer about them is a complete answer.
157
+ degraded: target.unreadable.length > 0,
158
+ errors: [],
159
+ warnings: target.unreadable,
160
+ notices: target.notices,
161
+ };
162
+ if (!target.system.components.length)
163
+ return report;
164
+ // A check is about the versions on disk now, whatever date an SBOM file carries.
165
+ const system = { ...target.system, updated_at: new Date(now).toISOString() };
166
+ const inventory = { systems: [system] };
167
+ const config = parseConfig({
168
+ version: 1,
169
+ sources: { cve_now: false, hacker_news: false, osv: true, github: false, kev, epss },
170
+ });
171
+ const store = new Store(':memory:');
172
+ try {
173
+ const scan = await runScan({
174
+ config,
175
+ inventory,
176
+ store,
177
+ now,
178
+ ...(options.http ? { http: options.http } : {}),
179
+ ...(options.signal ? { signal: options.signal } : {}),
180
+ });
181
+ const evidence = new Map(store.evidence().map((item) => [item.id, item]));
182
+ const components = new Map(system.components.map((component) => [component.id, component]));
183
+ report.degraded ||= scan.degraded;
184
+ report.errors = scan.errors.map((error) => `${error.source}: ${error.message}`);
185
+ for (const finding of scan.findings) {
186
+ if (finding.category === 'health') {
187
+ if (!report.errors.includes(finding.summary))
188
+ report.errors.push(cleanText(finding.summary, 300));
189
+ continue;
190
+ }
191
+ if (finding.active === false || finding.withdrawn)
192
+ continue;
193
+ if (finding.applicability !== 'affected' && finding.applicability !== 'unknown')
194
+ continue;
195
+ const component = finding.component_id ? components.get(finding.component_id) : undefined;
196
+ if (!component)
197
+ continue;
198
+ report.findings.push(toFinding(finding, component, evidence, target.locations));
199
+ }
200
+ }
201
+ finally {
202
+ store.close();
203
+ }
204
+ report.findings.sort(compareFindings);
205
+ return report;
206
+ }
207
+ function toFinding(finding, component, evidence, locations) {
208
+ const records = finding.evidence_ids.map((id) => evidence.get(id)).filter((item) => item !== undefined);
209
+ // A known-exploited entry is cited beside the advisory; the advisory names the problem.
210
+ const primary = records.find((item) => item.kind === 'advisory') ?? records[0];
211
+ const id = primary ? primary.id.replace(/^[a-z_]+:/, '') : finding.event_id;
212
+ // Identifiers keep their own case: OSV answers GHSA-xxxx-xxxx-xxxx, not GHSA-XXXX-XXXX-XXXX.
213
+ const aliases = uniqueIds(records.flatMap((item) => item.aliases ?? [])).filter((alias) => alias.toUpperCase() !== id.toUpperCase());
214
+ // OSV's MAL- records, and GitHub advisories that say the package itself is malicious (crossenv).
215
+ const malware = finding.category === 'malware' ||
216
+ records.some((item) => item.malware) ||
217
+ /\bmalicious (?:package|code|version|release)|\b(?:is|contains|embedded) malware\b/i.test(finding.title);
218
+ const purl = component.purl;
219
+ const files = (purl ? locations.get(purl) : undefined) ??
220
+ (component.note?.startsWith('found in ')
221
+ ? component.note.slice('found in '.length).split(/,\s*/).filter(Boolean)
222
+ : []);
223
+ return {
224
+ id,
225
+ aliases,
226
+ title: finding.title,
227
+ severity: finding.source_severity,
228
+ priority: malware ? 'critical' : finding.priority,
229
+ applicability: finding.applicability === 'affected' ? 'affected' : 'unknown',
230
+ exploited: finding.exploited,
231
+ malware,
232
+ package: {
233
+ ecosystem: component.ecosystem,
234
+ name: component.name,
235
+ ...(component.version ? { version: component.version } : {}),
236
+ },
237
+ files,
238
+ ...(finding.fix && fixesAbove(finding.fix, component.version)
239
+ ? { fixed: fixesAbove(finding.fix, component.version) }
240
+ : {}),
241
+ ...(primary?.url ? { url: primary.url } : finding.urls[0] ? { url: finding.urls[0] } : {}),
242
+ ...(finding.epss ? { epss: finding.epss } : {}),
243
+ reasons: finding.reasons,
244
+ };
245
+ }
246
+ /** CVE first (what people search for), then GHSA, then ecosystem IDs; BIT- mirrors last. */
247
+ function idOrder(id) {
248
+ return /^CVE-/i.test(id) ? 0 : /^GHSA-/i.test(id) ? 1 : /^BIT-/i.test(id) ? 3 : 2;
249
+ }
250
+ function uniqueIds(ids) {
251
+ const seen = new Map();
252
+ for (const id of ids)
253
+ if (!seen.has(id.toUpperCase()))
254
+ seen.set(id.toUpperCase(), id);
255
+ return [...seen.values()].sort((a, b) => idOrder(a) - idOrder(b) || a.localeCompare(b));
256
+ }
257
+ /**
258
+ * A git commit ID: 7 to 64 hex digits with at least one letter, or a full 40- or 64-digit ID.
259
+ * Date-style versions (org.json 20230227, pdfminer.six 20251107) are all digits and stay versions.
260
+ */
261
+ export function isCommitId(text) {
262
+ return (/^[0-9a-f]{40}$|^[0-9a-f]{64}$/i.test(text) || (/^[0-9a-f]{7,64}$/i.test(text) && /[a-f]/i.test(text)));
263
+ }
264
+ /** A version that compares, or undefined: commit IDs and other text never pass for a version. */
265
+ export function comparable(version) {
266
+ const text = version.trim();
267
+ if (!/^v?\d/.test(text) || isCommitId(text))
268
+ return undefined;
269
+ return valid(text) ?? coerce(text)?.version ?? undefined;
270
+ }
271
+ /**
272
+ * The fixed versions worth showing, from an advisory's fix list ("1.2.6; 0.2.4, 1.2.6"): each once,
273
+ * in version order, without commit IDs, and, when the installed version is known, only those above
274
+ * it (an advisory for several release lines lists a fix per line, and "upgrade to 0.2.4" is no
275
+ * advice for 1.2.5). Versions that do not compare are kept as they are.
276
+ */
277
+ export function fixesAbove(fix, installed) {
278
+ const seen = new Set();
279
+ const versions = [];
280
+ for (const raw of fix.split(/[;,]/)) {
281
+ const version = raw.trim();
282
+ if (!version || isCommitId(version) || seen.has(version))
283
+ continue;
284
+ seen.add(version);
285
+ versions.push(version);
286
+ }
287
+ versions.sort((a, b) => {
288
+ const [x, y] = [comparable(a), comparable(b)];
289
+ return x && y ? (gt(x, y) ? 1 : gt(y, x) ? -1 : 0) : x ? -1 : y ? 1 : a.localeCompare(b);
290
+ });
291
+ const current = installed ? comparable(installed) : undefined;
292
+ if (!current)
293
+ return versions.join('; ') || undefined;
294
+ const kept = versions.filter((version) => {
295
+ const candidate = comparable(version);
296
+ return !candidate || gt(candidate, current);
297
+ });
298
+ return (kept.length ? kept : versions).join('; ') || undefined;
299
+ }
300
+ function rank(finding) {
301
+ return ((finding.malware ? 200 : 0) +
302
+ (finding.exploited ? 100 : 0) +
303
+ level(finding) * 10 +
304
+ SEVERITY_ORDER.indexOf(finding.severity));
305
+ }
306
+ function compareFindings(a, b) {
307
+ return (rank(b) - rank(a) ||
308
+ (a.applicability === b.applicability ? 0 : a.applicability === 'affected' ? -1 : 1) ||
309
+ a.package.name.localeCompare(b.package.name) ||
310
+ a.id.localeCompare(b.id));
311
+ }
312
+ /** Reads a project's dependency files (or an SBOM) and checks every package against OSV. */
313
+ export async function checkProject(options = {}) {
314
+ return run(projectTarget(options), options);
315
+ }
316
+ /** Checks named packages, such as one an agent is about to add or upgrade to. */
317
+ export async function checkPackages(packages, options = {}) {
318
+ if (!packages.length)
319
+ throw new Error('Name at least one package.');
320
+ if (packages.length > 100)
321
+ throw new Error('Check at most 100 packages at a time.');
322
+ const components = packages.map((item, index) => {
323
+ const ecosystem = normalizeEcosystem(item.ecosystem);
324
+ const name = normalizePackageName(ecosystem, item.name);
325
+ if (!name)
326
+ throw new Error('Package name is empty.');
327
+ const version = item.version?.trim() ? exactLibraryVersion(item.version.trim(), ecosystem) : undefined;
328
+ return {
329
+ id: `package:${index}`,
330
+ ecosystem,
331
+ name,
332
+ ...(version ? { version } : {}),
333
+ provenance: { source: 'check', reference: 'request' },
334
+ };
335
+ });
336
+ const target = {
337
+ kind: 'packages',
338
+ label: packages.map((item) => `${item.name}${item.version ? `@${item.version}` : ''}`).join(', '),
339
+ system: blankSystem('packages', components),
340
+ files: [],
341
+ ecosystems: [...new Set(components.map((component) => component.ecosystem))].sort(),
342
+ packages: components.length,
343
+ unversioned: components.filter((component) => !component.version).length,
344
+ unreadable: [],
345
+ notices: [],
346
+ locations: new Map(),
347
+ };
348
+ return run(target, options);
349
+ }
350
+ function git(root, args, maxBuffer = 64 * 1024 * 1024) {
351
+ // A project's own .git/config can name programs git runs for some commands (core.fsmonitor runs
352
+ // on ls-files): those are switched off, so no project code runs.
353
+ return execFileSync('git', ['-C', root, '-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false', ...args], {
354
+ maxBuffer,
355
+ stdio: ['ignore', 'pipe', 'pipe'],
356
+ // The check makes no requests besides its sources: a partial clone must not fetch from its remote.
357
+ env: { ...process.env, GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0' },
358
+ });
359
+ }
360
+ function gitError(error) {
361
+ if (error.code === 'ENOENT')
362
+ return 'git is not installed here; the container image has none, so use the npm package for change checks';
363
+ const stderr = error.stderr?.toString().trim();
364
+ return cleanText(stderr || (error instanceof Error ? error.message : 'git failed'), 300);
365
+ }
366
+ function isInside(child, parent) {
367
+ const rel = relative(parent, child);
368
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
369
+ }
370
+ function gitProject(project) {
371
+ const root = realpathSync.native(resolve(project));
372
+ if (!statSync(root).isDirectory())
373
+ throw new Error('A change can only be checked for a project folder.');
374
+ try {
375
+ const top = git(root, ['rev-parse', '--show-toplevel']).toString().trim();
376
+ // git's own prefix, so a path typed in another letter case on macOS or Windows still matches.
377
+ const prefix = git(root, ['rev-parse', '--show-prefix']).toString().trim().replace(/\/$/, '');
378
+ return { root, top, prefix };
379
+ }
380
+ catch (error) {
381
+ throw new Error(`Not a git repository (${gitError(error)}).`);
382
+ }
383
+ }
384
+ function checkRef(ref, shown) {
385
+ if (!ref || ref.startsWith('-') || ref.length > 200 || /[\s\0]/.test(ref))
386
+ throw new Error(`base must be a git ref such as HEAD, main or origin/main (${shown}).`);
387
+ }
388
+ /**
389
+ * The commit to compare with. `REF...` (three dots, as in `git diff`) is the point where the current
390
+ * branch left REF, so a branch that is behind REF is not blamed for what REF changed since.
391
+ */
392
+ function baseCommit(gp, base) {
393
+ const branchPoint = base.endsWith('...');
394
+ const ref = branchPoint ? base.slice(0, -3) : base;
395
+ checkRef(ref, base);
396
+ let commit;
397
+ try {
398
+ commit = git(gp.root, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${ref}^{commit}`])
399
+ .toString()
400
+ .trim();
401
+ }
402
+ catch {
403
+ throw new Error(`git does not know ${ref}. Fetch it first, or name a commit that exists here.`);
404
+ }
405
+ if (!branchPoint)
406
+ return commit;
407
+ try {
408
+ return git(gp.root, ['merge-base', commit, 'HEAD']).toString().trim();
409
+ }
410
+ catch (error) {
411
+ throw new Error(`${ref} and HEAD have no common commit (${gitError(error)}).`);
412
+ }
413
+ }
414
+ /** Copies the given files into `folder/<project name>/` at their paths relative to the project. */
415
+ function stage(gp, files, what) {
416
+ const folder = mkdtempSync(join(tmpdir(), 'security-watch-change-'));
417
+ const project = join(folder, basename(gp.root));
418
+ const skipped = [];
419
+ const skippedPaths = [];
420
+ try {
421
+ mkdirSync(project);
422
+ let total = 0;
423
+ for (const file of files) {
424
+ // The same limit and wording as reading the project directly, so the check counts as incomplete.
425
+ if (file.size > MAX_GIT_BYTES) {
426
+ skipped.push(`${file.path}: larger than 20 MiB; skipped.`);
427
+ skippedPaths.push(file.path);
428
+ continue;
429
+ }
430
+ total += file.size;
431
+ if (total > MAX_GIT_TOTAL)
432
+ throw new Error(`Dependency files in ${what} exceed 200 MiB.`);
433
+ let content;
434
+ try {
435
+ content = file.read();
436
+ }
437
+ catch (error) {
438
+ skipped.push(`${file.path}: could not be read (${gitError(error)}); skipped.`);
439
+ skippedPaths.push(file.path);
440
+ continue;
441
+ }
442
+ const destination = join(project, ...file.path.split('/'));
443
+ mkdirSync(dirname(destination), { recursive: true });
444
+ writeFileSync(destination, content);
445
+ }
446
+ return { folder, project, skipped, skippedPaths };
447
+ }
448
+ catch (error) {
449
+ rmSync(folder, { recursive: true, force: true });
450
+ throw error;
451
+ }
452
+ }
453
+ function relativeToProject(gp, path) {
454
+ if (!gp.prefix)
455
+ return path;
456
+ return path.startsWith(`${gp.prefix}/`) ? path.slice(gp.prefix.length + 1) : undefined;
457
+ }
458
+ /**
459
+ * Writes the dependency files of `project` as they were at `base` into a new temporary folder.
460
+ * Only files the project reader would pick up are taken, with `git cat-file`; nothing is checked
461
+ * out and no repository code runs. Submodules are not followed.
462
+ */
463
+ export function dependencyFilesAt(project, base) {
464
+ const gp = gitProject(project);
465
+ const commit = baseCommit(gp, base);
466
+ const listed = git(gp.top, [
467
+ 'ls-tree',
468
+ '-r',
469
+ '-z',
470
+ '-l',
471
+ '--full-tree',
472
+ commit,
473
+ '--',
474
+ ...(gp.prefix ? [gp.prefix] : []),
475
+ ])
476
+ .toString()
477
+ .split('\0')
478
+ .filter(Boolean);
479
+ const files = [];
480
+ for (const line of listed) {
481
+ const tab = line.indexOf('\t');
482
+ const [mode, type, object, size] = line.slice(0, tab).split(/\s+/);
483
+ const path = relativeToProject(gp, line.slice(tab + 1));
484
+ if (type !== 'blob' || mode === '120000' || !object || path === undefined)
485
+ continue;
486
+ if (!isDependencyFilePath(path, basename(gp.root)))
487
+ continue;
488
+ files.push({
489
+ path,
490
+ size: Number(size),
491
+ read: () => git(gp.top, ['cat-file', 'blob', object], MAX_GIT_BYTES + 1),
492
+ });
493
+ if (files.length > MAX_GIT_FILES)
494
+ throw new Error(`More than ${MAX_GIT_FILES} dependency files at ${base}; check a smaller folder.`);
495
+ }
496
+ return { ...stage(gp, files, base), commit };
497
+ }
498
+ /**
499
+ * The dependency files of the working tree that git tracks or would track: tracked files as they
500
+ * are on disk, and untracked files that are not ignored. Submodules, nested repositories and
501
+ * ignored folders are left out, as they are at the base.
502
+ */
503
+ export function dependencyFilesInWorkingTree(project) {
504
+ const gp = gitProject(project);
505
+ const listed = git(gp.top, [
506
+ 'ls-files',
507
+ '-z',
508
+ '-c',
509
+ '-o',
510
+ '--exclude-standard',
511
+ '--',
512
+ ...(gp.prefix ? [gp.prefix] : []),
513
+ ])
514
+ .toString()
515
+ .split('\0')
516
+ .filter(Boolean);
517
+ const files = [];
518
+ const outside = [];
519
+ const seen = new Set();
520
+ for (const entry of listed) {
521
+ const path = relativeToProject(gp, entry);
522
+ if (path === undefined || seen.has(path) || !isDependencyFilePath(path, basename(gp.root)))
523
+ continue;
524
+ seen.add(path);
525
+ const absolute = join(gp.top, ...entry.split('/'));
526
+ let stat;
527
+ try {
528
+ stat = lstatSync(absolute);
529
+ }
530
+ catch {
531
+ continue; // tracked but deleted in the working tree
532
+ }
533
+ if (!stat.isFile())
534
+ continue; // a link, or a submodule's folder
535
+ // A folder on the way can be a link that leads out of the project, as the file itself cannot.
536
+ if (!isInside(realpathSync.native(absolute), gp.root)) {
537
+ outside.push(path);
538
+ continue;
539
+ }
540
+ files.push({ path, size: stat.size, read: () => readFileSync(absolute) });
541
+ if (files.length > MAX_GIT_FILES)
542
+ throw new Error(`More than ${MAX_GIT_FILES} dependency files in the working tree; check a smaller folder.`);
543
+ }
544
+ const staged = stage(gp, files, 'the working tree');
545
+ for (const path of outside) {
546
+ staged.skipped.push(`${path}: reached through a link that leads outside the project; skipped.`);
547
+ staged.skippedPaths.push(path);
548
+ }
549
+ return staged;
550
+ }
551
+ function findingKey(finding) {
552
+ return JSON.stringify([finding.id.toUpperCase(), finding.package.ecosystem, finding.package.name]);
553
+ }
554
+ function packageVersions(target) {
555
+ const out = new Map();
556
+ for (const component of target.system.components) {
557
+ const key = `${component.ecosystem}:${component.name}`;
558
+ const versions = out.get(key);
559
+ out.set(key, versions ? `${versions}, ${component.version ?? '?'}` : (component.version ?? '?'));
560
+ }
561
+ return out;
562
+ }
563
+ function stagedTarget(staged, options, label) {
564
+ const target = projectTarget({ ...options, project: staged.project });
565
+ target.label = label;
566
+ target.unreadable.push(...staged.skipped);
567
+ return target;
568
+ }
569
+ /**
570
+ * Compares a project's dependencies at a git ref with the working tree and reports what the change
571
+ * added and fixed. Both sides are the files git knows: the base from its objects, the working tree
572
+ * as it is on disk (tracked, plus untracked files that are not ignored).
573
+ */
574
+ export async function checkChange(options) {
575
+ const project = resolve(options.project ?? '.');
576
+ const before = dependencyFilesAt(project, options.base);
577
+ let after;
578
+ try {
579
+ after = dependencyFilesInWorkingTree(project);
580
+ // A file left out on one side is left out on both, or its packages would read as removed (or
581
+ // added) and their advisories as fixed (or brought in).
582
+ for (const path of after.skippedPaths)
583
+ rmSync(join(before.project, ...path.split('/')), { force: true });
584
+ for (const path of before.skippedPaths)
585
+ rmSync(join(after.project, ...path.split('/')), { force: true });
586
+ const baseTarget = stagedTarget(before, options, `${options.base} (${before.commit.slice(0, 12)})`);
587
+ const headTarget = stagedTarget(after, options, realpathSync(project));
588
+ const http = options.http ?? cachingHttp();
589
+ const [old, now] = await Promise.all([
590
+ run(baseTarget, { ...options, http }),
591
+ run(headTarget, { ...options, http }),
592
+ ]);
593
+ const beforeKeys = new Map(old.findings.map((finding) => [findingKey(finding), finding]));
594
+ const afterKeys = new Set(now.findings.map(findingKey));
595
+ const added = now.findings.filter((finding) => !beforeKeys.has(findingKey(finding)));
596
+ const resolved = old.findings.filter((finding) => !afterKeys.has(findingKey(finding)));
597
+ const oldPackages = packageVersions(baseTarget);
598
+ const newPackages = packageVersions(headTarget);
599
+ const packages = { added: [], removed: [], changed: [] };
600
+ for (const [key, version] of newPackages) {
601
+ const was = oldPackages.get(key);
602
+ if (was === undefined)
603
+ packages.added.push(`${key}@${version}`);
604
+ else if (was !== version)
605
+ packages.changed.push(`${key} ${was} -> ${version}`);
606
+ }
607
+ for (const [key, version] of oldPackages)
608
+ if (!newPackages.has(key))
609
+ packages.removed.push(`${key}@${version}`);
610
+ for (const list of Object.values(packages))
611
+ list.sort();
612
+ if (old.degraded) {
613
+ now.degraded = true;
614
+ now.errors.push(...old.errors.map((error) => `at ${options.base}: ${error}`));
615
+ now.warnings.push(...old.warnings.map((warning) => `at ${options.base}: ${warning}`));
616
+ }
617
+ return {
618
+ base: options.base,
619
+ commit: before.commit,
620
+ head: now,
621
+ added,
622
+ resolved,
623
+ unchanged: now.findings.length - added.length,
624
+ packages,
625
+ };
626
+ }
627
+ finally {
628
+ rmSync(before.folder, { recursive: true, force: true });
629
+ if (after)
630
+ rmSync(after.folder, { recursive: true, force: true });
631
+ }
632
+ }
633
+ async function osvRecordById(http, id, now, signal) {
634
+ signal?.throwIfAborted();
635
+ const response = await http(`${OSV}/vulns/${encodeURIComponent(id)}`, { maxBytes: 8_000_000 });
636
+ if (response.status === 404)
637
+ return undefined;
638
+ if (response.status !== 200)
639
+ throw new Error(`OSV answered HTTP ${response.status} for ${id}.`);
640
+ const raw = JSON.parse(response.body);
641
+ try {
642
+ return osvEvidence(raw, id, now);
643
+ }
644
+ catch {
645
+ // CVE records converted from NVD can name source-code ranges the monitor's reader refuses; the
646
+ // title, aliases and description still answer the question, and aliases lead to package records.
647
+ const data = (typeof raw === 'object' && raw !== null ? raw : {});
648
+ const text = (value) => (typeof value === 'string' ? cleanText(value, 2000) : undefined);
649
+ const aliases = Array.isArray(data.aliases)
650
+ ? data.aliases.filter((alias) => typeof alias === 'string')
651
+ : [];
652
+ const summary = text(data.summary);
653
+ const details = text(data.details);
654
+ return {
655
+ id: `osv:${id}`,
656
+ source: 'osv',
657
+ kind: 'advisory',
658
+ title: summary ?? details?.split(/(?<=\.)\s/)[0]?.slice(0, 200) ?? id,
659
+ url: `https://osv.dev/vulnerability/${encodeURIComponent(id)}`,
660
+ description: details ?? summary ?? '',
661
+ aliases: [id, ...aliases],
662
+ severity: 'unknown',
663
+ modified_at: new Date(now).toISOString(),
664
+ fetched_at: new Date(now).toISOString(),
665
+ packages: [],
666
+ };
667
+ }
668
+ }
669
+ function advisorySeverity(records, findings) {
670
+ const levels = [
671
+ ...records.map((item) => item.severity ?? 'unknown'),
672
+ ...findings.map((finding) => finding.severity),
673
+ ];
674
+ const top = levels.reduce((best, value) => (SEVERITY_ORDER.indexOf(value) > SEVERITY_ORDER.indexOf(best) ? value : best), 'unknown');
675
+ return top === 'unknown' ? undefined : top;
676
+ }
677
+ /** CVE and GHSA identifiers in the case OSV uses; anything else as typed. */
678
+ export function normalizeAdvisoryId(value) {
679
+ const id = value.trim();
680
+ if (/^ghsa-/i.test(id))
681
+ return `GHSA-${id.slice(5).toLowerCase()}`;
682
+ if (/^cve-/i.test(id))
683
+ return id.toUpperCase();
684
+ return id;
685
+ }
686
+ /**
687
+ * Answers "does this advisory concern the project?": looks the identifier up in OSV (CVE, GHSA,
688
+ * PYSEC, RUSTSEC, GO, MAL ...), follows aliases to the records that name packages, and checks
689
+ * the project.
690
+ */
691
+ export async function checkAdvisory(advisory, options = {}) {
692
+ const id = normalizeAdvisoryId(advisory);
693
+ if (!ADVISORY_ID.test(id) || id.length > 100)
694
+ throw new Error('Give an advisory ID such as CVE-2021-44906, GHSA-xvch-5gv4-984h or PYSEC-2024-1.');
695
+ const now = options.now ?? Date.now();
696
+ const http = options.http ?? cachingHttp();
697
+ const target = projectTarget(options);
698
+ const lookup = async () => (await osvRecordById(http, id, now, options.signal)) ??
699
+ // OSV identifiers are case-sensitive (openSUSE-SU-..., GHSA-xxxx): try the upper-case form too.
700
+ (id.toUpperCase() !== id ? await osvRecordById(http, id.toUpperCase(), now, options.signal) : undefined);
701
+ const [project, record] = await Promise.all([run(target, { ...options, http }), lookup()]);
702
+ const records = record ? [record] : [];
703
+ if (record && !(record.packages ?? []).length)
704
+ for (const alias of (record.aliases ?? []).filter((alias) => alias.toUpperCase() !== id).slice(0, 4))
705
+ try {
706
+ const other = await osvRecordById(http, alias, now, options.signal);
707
+ if (other)
708
+ records.push(other);
709
+ }
710
+ catch (error) {
711
+ if (options.signal?.aborted)
712
+ throw error;
713
+ /* The first record still answers; an alias that fails only loses package detail. */
714
+ }
715
+ const names = new Set([id, ...records.flatMap((item) => [item.id.replace(/^osv:/, ''), ...(item.aliases ?? [])])].map((name) => name.toUpperCase()));
716
+ const findings = project.findings.filter((finding) => names.has(finding.id.toUpperCase()) || finding.aliases.some((alias) => names.has(alias.toUpperCase())));
717
+ const packages = new Map();
718
+ for (const item of records)
719
+ for (const claim of item.packages ?? []) {
720
+ const key = `${claim.ecosystem}\0${claim.name}\0${claim.range ?? ''}`;
721
+ const known = packages.get(key);
722
+ // One package often has an entry per release line (urllib3 1.26.17 and 2.0.6): keep every fix.
723
+ const fixed = fixesAbove([known?.fixed, claim.fixed].filter(Boolean).join('; '), undefined);
724
+ packages.set(key, {
725
+ ecosystem: claim.ecosystem,
726
+ name: claim.name,
727
+ ...(claim.range ? { range: claim.range } : {}),
728
+ ...(fixed ? { fixed } : {}),
729
+ });
730
+ }
731
+ const affectedPackages = new Set(findings.map((finding) => `${finding.package.ecosystem}:${finding.package.name}`));
732
+ const present = new Set();
733
+ for (const claim of packages.values())
734
+ for (const component of target.system.components)
735
+ if (ECOSYSTEMS.includes(claim.ecosystem) &&
736
+ component.ecosystem === claim.ecosystem &&
737
+ component.name.toLowerCase() ===
738
+ normalizePackageName(component.ecosystem, claim.name).toLowerCase() &&
739
+ !affectedPackages.has(`${component.ecosystem}:${component.name}`))
740
+ present.add(`${component.ecosystem}:${component.name}@${component.version ?? '?'}`);
741
+ const main = records[0];
742
+ return {
743
+ id,
744
+ found: Boolean(record),
745
+ ...(main?.title ? { title: main.title } : {}),
746
+ ...(main?.description ? { summary: cleanText(main.description, 600) } : {}),
747
+ aliases: uniqueIds(records.flatMap((item) => [item.id.replace(/^osv:/, ''), ...(item.aliases ?? [])])).filter((alias) => alias.toUpperCase() !== id.toUpperCase()),
748
+ ...(main?.url ? { url: main.url } : {}),
749
+ // The highest severity any of its records gives, so the header never reads lower than a finding.
750
+ ...(advisorySeverity(records, findings) ? { severity: advisorySeverity(records, findings) } : {}),
751
+ packages: [...packages.values()].slice(0, 50),
752
+ findings,
753
+ present_not_affected: [...present].sort(),
754
+ project,
755
+ };
756
+ }
757
+ // Text for people and agents.
758
+ function plural(count, word) {
759
+ if (count === 1)
760
+ return `1 ${word}`;
761
+ return `${count} ${word.endsWith('y') && !/[aeiou]y$/.test(word) ? `${word.slice(0, -1)}ies` : `${word}s`}`;
762
+ }
763
+ /**
764
+ * The level a finding is filtered and gated at. An advisory without a severity (many GO- and some
765
+ * PYSEC records) is not "low": it counts as medium, so it is shown by default and fails
766
+ * `--fail-on medium`, and the output says how many there are.
767
+ */
768
+ function level(finding) {
769
+ return finding.priority === 'unknown'
770
+ ? SEVERITY_ORDER.indexOf('medium')
771
+ : SEVERITY_ORDER.indexOf(finding.priority);
772
+ }
773
+ function atLeast(finding, min) {
774
+ return finding.malware || finding.exploited || level(finding) >= SEVERITY_ORDER.indexOf(min);
775
+ }
776
+ /**
777
+ * Whether a finding fails a check at `failOn`. Malware always does. An installed version that is
778
+ * affected fails when it is known exploited or at or above the level. A package without an exact
779
+ * version ("check by hand") does not: nothing says the version in use is affected.
780
+ */
781
+ export function failsAt(finding, failOn) {
782
+ if (failOn === 'none')
783
+ return false;
784
+ if (finding.malware)
785
+ return true;
786
+ if (finding.applicability !== 'affected')
787
+ return false;
788
+ return finding.exploited || level(finding) >= SEVERITY_ORDER.indexOf(failOn);
789
+ }
790
+ export function findingLine(finding, kind = 'project') {
791
+ const name = `${finding.package.ecosystem} ${finding.package.name}${finding.package.version ? ` ${finding.package.version}` : ''}`;
792
+ const flags = [
793
+ finding.malware ? 'MALWARE' : '',
794
+ finding.exploited ? 'known exploited (CISA KEV)' : '',
795
+ finding.applicability === 'unknown'
796
+ ? kind === 'packages'
797
+ ? 'no version given'
798
+ : 'no exact version: check by hand'
799
+ : '',
800
+ finding.priority === 'unknown' ? 'the advisory gives no severity' : '',
801
+ finding.epss ? `EPSS ${(finding.epss.probability * 100).toFixed(1)}%` : '',
802
+ ].filter(Boolean);
803
+ const ids = [finding.id, ...finding.aliases.slice(0, 3)].join(', ');
804
+ return [
805
+ `- [${finding.priority}] ${name}: ${finding.title} (${ids})${flags.length ? ` [${flags.join('; ')}]` : ''}`,
806
+ ` ${finding.malware ? 'Fix: remove this package and rotate any credentials it could reach.' : finding.fixed ? (finding.applicability === 'affected' ? `Fix: upgrade to ${finding.fixed}.` : `Fixed in ${finding.fixed}: use at least the one on the release line you run.`) : 'Fix: no fixed version listed.'}${finding.files.length ? ` In: ${finding.files.slice(0, 4).join(', ')}${finding.files.length > 4 ? ` and ${finding.files.length - 4} more` : ''}.` : ''}${finding.url ? ` ${finding.url}` : ''}`,
807
+ ].join('\n');
808
+ }
809
+ /** The release line a version belongs to: major.minor, the unit projects backport fixes to. */
810
+ function line(version) {
811
+ return `${major(version)}.${minor(version)}`;
812
+ }
813
+ /** Whether `candidate` is fixed for an advisory that lists these fixed versions, one per line. */
814
+ function fixedBy(candidate, fixes) {
815
+ const same = fixes.filter((fix) => line(fix) === line(candidate));
816
+ if (same.length)
817
+ return same.some((fix) => !gt(fix, candidate));
818
+ // A line the advisory does not mention is fixed only if it is newer than every fix it lists.
819
+ return fixes.every((fix) => !gt(fix, candidate));
820
+ }
821
+ /**
822
+ * One line per package with several findings: the lowest listed fixed version that fixes all of
823
+ * them, each judged on its own release line, so that an agent upgrades once instead of once per
824
+ * finding. Nothing is said when no listed version fixes them all.
825
+ */
826
+ export function upgradeSummary(findings) {
827
+ const groups = new Map();
828
+ for (const finding of findings) {
829
+ if (finding.malware || finding.applicability !== 'affected' || !finding.package.version)
830
+ continue;
831
+ const key = `${finding.package.ecosystem} ${finding.package.name} ${finding.package.version}`;
832
+ groups.set(key, [...(groups.get(key) ?? []), finding]);
833
+ }
834
+ const out = [];
835
+ for (const [key, group] of groups) {
836
+ if (group.length < 2)
837
+ continue;
838
+ const installed = comparable(group[0].package.version);
839
+ if (!installed)
840
+ continue;
841
+ // The version as the advisory writes it, for each form that compares (20260719, not 20260719.0.0).
842
+ const written = new Map();
843
+ const fixLists = group.map((finding) => (finding.fixed ?? '')
844
+ .split(/[;,]/)
845
+ .map((fix) => {
846
+ const value = comparable(fix);
847
+ if (value && !written.has(value))
848
+ written.set(value, fix.trim());
849
+ return value;
850
+ })
851
+ .filter((fix) => fix !== undefined));
852
+ const open = fixLists.filter((fixes) => !fixes.length).length;
853
+ const lists = fixLists.filter((fixes) => fixes.length);
854
+ if (!lists.length)
855
+ continue;
856
+ const candidates = [...new Set(lists.flat())]
857
+ .filter((fix) => gt(fix, installed))
858
+ .sort((a, b) => (gt(a, b) ? 1 : -1));
859
+ const target = candidates.find((candidate) => lists.every((fixes) => fixedBy(candidate, fixes)));
860
+ if (!target)
861
+ continue;
862
+ const shown = written.get(target) ?? target;
863
+ // Release lines exist for dotted versions (5.2.17 is on 5.2); a date version has none.
864
+ const lined = /^v?\d+\.\d+/.test(shown);
865
+ const count = open
866
+ ? `${lists.length} of ${group.length}; ${open} name no fixed version`
867
+ : `all ${group.length}`;
868
+ out.push(lined
869
+ ? `- ${key}: upgrading to ${shown} (or a later ${line(target)}.x release) fixes ${count}. A newer release line is not checked here: check it before moving to one.`
870
+ : `- ${key}: upgrading to ${shown} or later fixes ${count}.`);
871
+ }
872
+ return out;
873
+ }
874
+ /** Said first, so that a reader who stops early knows the answer is partial. */
875
+ function incomplete(report) {
876
+ if (!report.degraded && !report.errors.length && !report.warnings.length)
877
+ return [];
878
+ const out = ['INCOMPLETE: findings may be missing.'];
879
+ for (const warning of report.warnings.slice(0, 10))
880
+ out.push(`- not read: ${warning}`);
881
+ if (report.warnings.length > 10)
882
+ out.push(`- and ${report.warnings.length - 10} more files not read`);
883
+ for (const error of report.errors.slice(0, 10))
884
+ out.push(`- source failed: ${error}`);
885
+ return out;
886
+ }
887
+ function notes(report) {
888
+ if (!report.notices.length)
889
+ return [];
890
+ return [
891
+ '',
892
+ 'Notes:',
893
+ ...report.notices.slice(0, 8).map((notice) => `- ${notice}`),
894
+ ...(report.notices.length > 8 ? [`- and ${report.notices.length - 8} more`] : []),
895
+ ];
896
+ }
897
+ function sourcesText(report) {
898
+ return report.sources
899
+ .map((source) => ({ osv: 'OSV', kev: 'CISA KEV', epss: 'EPSS' })[source] ?? source)
900
+ .join(', ');
901
+ }
902
+ function hiddenText(total, shown, min) {
903
+ return shown.length < total.length ? ` (${total.length - shown.length} below ${min} not shown)` : '';
904
+ }
905
+ export function formatCheckReport(report, min = 'low') {
906
+ const shown = report.findings.filter((finding) => atLeast(finding, min));
907
+ const files = report.files.filter((file) => file.packages);
908
+ const out = [
909
+ `Checked ${plural(report.packages, 'package')}${report.ecosystems.length ? ` (${report.ecosystems.join(', ')})` : ''}${files.length ? ` from ${plural(files.length, 'file')}` : ''} in ${report.target} against ${sourcesText(report)} at ${report.checked_at}.`,
910
+ ...incomplete(report),
911
+ ];
912
+ if (!report.packages)
913
+ out.push('No dependencies found. Supported files: lockfiles and manifests for npm, Python, Go, Rust, PHP, Ruby, Java, .NET, Dart, Elixir, Swift and Haskell, or a CycloneDX/SPDX SBOM.');
914
+ if (report.unversioned)
915
+ out.push(report.kind === 'packages'
916
+ ? `${plural(report.unversioned, 'package')} named without a version: every advisory for ${report.unversioned === 1 ? 'it is' : 'them is'} listed.`
917
+ : `${plural(report.unversioned, 'package')} had no exact version${report.files.length ? ' (a manifest without its lockfile)' : ''} and could only be checked by name.`);
918
+ const affected = report.findings.filter((finding) => finding.applicability === 'affected');
919
+ const byHand = report.findings.length - affected.length;
920
+ const noSeverity = report.findings.filter((finding) => finding.priority === 'unknown').length;
921
+ if (report.packages)
922
+ out.push(report.findings.length
923
+ ? `${plural(affected.length, 'known vulnerability')} in ${report.kind === 'packages' ? 'these versions' : 'installed versions'}${byHand ? `, ${byHand} ${report.kind === 'packages' ? 'for packages named without a version' : 'to check by hand (no exact version)'}` : ''}${noSeverity ? `; ${noSeverity} without a severity in the advisory` : ''}${hiddenText(report.findings, shown, min)}:`
924
+ : report.degraded
925
+ ? 'No known vulnerabilities in the packages that could be checked.'
926
+ : 'No known vulnerabilities in these versions.');
927
+ out.push(...shown.map((finding) => findingLine(finding, report.kind)));
928
+ const upgrades = upgradeSummary(shown);
929
+ if (upgrades.length)
930
+ out.push('', 'Upgrades that fix several at once:', ...upgrades);
931
+ out.push(...notes(report));
932
+ return out.join('\n');
933
+ }
934
+ export function formatChangeReport(change, min = 'low') {
935
+ const { packages } = change;
936
+ const out = [
937
+ `Compared dependencies in ${change.head.target} at ${change.base} (${change.commit.slice(0, 12)}) with the working tree: ${plural(packages.added.length, 'package')} added, ${packages.removed.length} removed, ${packages.changed.length} changed.`,
938
+ ...incomplete(change.head),
939
+ ];
940
+ for (const [label, list] of [
941
+ ['Added', packages.added],
942
+ ['Changed', packages.changed],
943
+ ['Removed', packages.removed],
944
+ ])
945
+ if (list.length)
946
+ out.push(`${label}: ${list.slice(0, 15).join('; ')}${list.length > 15 ? `; and ${list.length - 15} more` : ''}`);
947
+ const added = change.added.filter((finding) => atLeast(finding, min));
948
+ out.push('', change.added.length
949
+ ? `The change brings in ${plural(change.added.length, 'known vulnerability')}${hiddenText(change.added, added, min)}:`
950
+ : 'The change brings in no known vulnerabilities.', ...added.map((finding) => findingLine(finding)));
951
+ const upgrades = upgradeSummary(added);
952
+ if (upgrades.length)
953
+ out.push('', 'Upgrades that fix several at once:', ...upgrades);
954
+ if (change.resolved.length)
955
+ out.push('', `It fixes ${change.resolved.length}:`, ...change.resolved
956
+ .slice(0, 20)
957
+ .map((finding) => `- ${finding.package.name}: ${finding.id} ${finding.title}`), ...(change.resolved.length > 20 ? [`- and ${change.resolved.length - 20} more`] : []));
958
+ if (change.unchanged)
959
+ out.push('', `${plural(change.unchanged, 'known vulnerability')} were there before and still are.`);
960
+ out.push(...notes(change.head));
961
+ return out.join('\n');
962
+ }
963
+ export function formatAdvisoryReport(report) {
964
+ const out = [];
965
+ if (!report.found)
966
+ out.push(`OSV has no record under ${report.id}. If it was published in the last hours, OSV may not have it yet; the vendor's advisory or GitHub's advisory database may.`);
967
+ else {
968
+ out.push(`${report.id}${report.title ? `: ${report.title}` : ''}${report.severity ? ` [${report.severity}]` : ''}`);
969
+ if (report.aliases.length)
970
+ out.push(`Also known as: ${report.aliases.slice(0, 8).join(', ')}`);
971
+ if (report.summary && !(report.title && report.summary.startsWith(report.title)))
972
+ out.push(report.summary);
973
+ if (report.packages.length)
974
+ out.push(`Packages it concerns: ${report.packages
975
+ .slice(0, 10)
976
+ .map((item) => `${item.ecosystem} ${item.name}${item.range ? ` ${item.range}` : ''}${item.fixed ? ` (fixed in ${item.fixed})` : ''}`)
977
+ .join('; ')}${report.packages.length > 10 ? `; and ${report.packages.length - 10} more` : ''}`);
978
+ else
979
+ out.push('The record names no package ecosystem Security Watch reads (it may concern an operating system, a product or source code).');
980
+ if (report.url)
981
+ out.push(report.url);
982
+ }
983
+ out.push('', `Project: ${report.project.target}`, ...incomplete(report.project));
984
+ const affected = report.findings.filter((finding) => finding.applicability === 'affected');
985
+ const unknown = report.findings.filter((finding) => finding.applicability !== 'affected');
986
+ if (affected.length)
987
+ out.push('This project IS affected:', ...affected.map((finding) => findingLine(finding)));
988
+ if (unknown.length)
989
+ out.push(`This project MAY be affected: it has the package without an exact version (no lockfile), so the version in use cannot be compared. Check the installed version against the ranges above:`, ...unknown.map((finding) => findingLine(finding)));
990
+ if (!report.findings.length) {
991
+ if (report.present_not_affected.length)
992
+ out.push(`This project has ${report.present_not_affected.join(', ')}, at versions the advisory does not list as affected.`);
993
+ else if (report.project.packages)
994
+ out.push(`This project ${report.project.degraded ? 'shows no' : 'is not affected: none of its'} ${plural(report.project.packages, 'package')}${report.project.degraded ? ' that could be read with an affected version' : ' is named with an affected version'}.`);
995
+ else
996
+ out.push('No dependencies were found in this project, so nothing could be matched.');
997
+ }
998
+ out.push(...notes(report.project));
999
+ return out.join('\n');
1000
+ }