npm-utils 0.6.1

Pure-Rust npm toolkit: resolve, download, install/ci, add/remove/upgrade, search, SBOM (CycloneDX/SPDX), and vulnerability audit (npm + OSV) — no Node.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Vulnerability auditing for a parsed `package-lock.json` — `npm audit`, pure Rust.
//!
//! The packages a lockfile pins ([`crate::sbom::components`]) are checked against one or more
//! **advisory sources** behind a small [`AdvisorySource`] trait, and the hits are distilled into an
//! [`AuditReport`]: which installed components are vulnerable, to which advisories, at what severity.
//!
//! Two sources ship in v1, both keyless and queried by default:
//! - [`npm::NpmRegistrySource`] — npm's native bulk-advisory endpoint (also honours a custom mirror).
//! - [`osv::OsvSource`] — the OSV (osv.dev) database, with structured affected-version ranges.
//!
//! The seam is deliberately open: a new source is one `impl AdvisorySource` plus one line where the
//! active sources are assembled (e.g. a future, feature-gated, API-key'd Snyk source).
//!
//! Everything except the sources' network calls is pure and unit-tested: [`dedup_advisories`]
//! collapses the same vulnerability reported by several sources, and [`build_report`] keeps only the
//! advisories whose vulnerable range actually contains the *installed* version — the guard against
//! the npm endpoint's range over-broadening — then groups and counts them.
//!
//! ```no_run
//! use npm_utils::{audit, package_json::lock::Lockfile, sbom};
//! # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//! let lock = Lockfile::parse(&std::fs::read_to_string("package-lock.json")?)?;
//! let components = sbom::components(&lock);
//! let sources: Vec<Box<dyn audit::AdvisorySource>> =
//!     vec![Box::new(audit::npm::NpmRegistrySource::new("https://registry.npmjs.org"))];
//! let report = audit::run_audit(&components, &sources);
//! print!("{}", audit::render_summary(&report));
//! # Ok(()) }
//! ```

use std::collections::{BTreeMap, BTreeSet};

use semver::Version;
use serde_json::{json, Map, Value};

use crate::package_json::spec::Range;
use crate::sbom::Component;

pub mod npm;
pub mod osv;

/// A normalized advisory severity. Ordered `Low < Moderate < High < Critical` so a `--audit-level`
/// threshold is a simple comparison. npm's vocabulary (`moderate`, not `medium`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    Low,
    Moderate,
    High,
    Critical,
}

impl Severity {
    /// Parse a severity word, case-insensitively, from either source's vocabulary: npm's
    /// `low`/`moderate`/`high`/`critical` and OSV's uppercase `CRITICAL` etc.; `medium` maps to
    /// [`Severity::Moderate`]. Anything else (`info`, `none`, empty, unknown) is `None` — below the
    /// lowest actionable bucket.
    pub fn from_str_loose(s: &str) -> Option<Severity> {
        match s.trim().to_ascii_lowercase().as_str() {
            "low" => Some(Severity::Low),
            "moderate" | "medium" => Some(Severity::Moderate),
            "high" => Some(Severity::High),
            "critical" => Some(Severity::Critical),
            _ => None,
        }
    }

    /// The lowercase wire/display word for this severity.
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Low => "low",
            Severity::Moderate => "moderate",
            Severity::High => "high",
            Severity::Critical => "critical",
        }
    }
}

/// Map a CVSS base score to a severity bucket (the CVSS v3 qualitative ranges): `<= 0` is `None`,
/// `< 4` Low, `< 7` Moderate, `< 9` High, else Critical. Used when a source gives a numeric score
/// but no severity word.
pub fn severity_from_cvss(score: f64) -> Option<Severity> {
    match score {
        s if s <= 0.0 => None,
        s if s < 4.0 => Some(Severity::Low),
        s if s < 7.0 => Some(Severity::Moderate),
        s if s < 9.0 => Some(Severity::High),
        _ => Some(Severity::Critical),
    }
}

/// One vulnerability advisory, normalized across sources into a single shape.
#[derive(Debug, Clone)]
pub struct Advisory {
    /// The reporting source's name (`"npm"`, `"osv"`, …) — matches [`AdvisorySource::name`].
    pub source: &'static str,
    /// The source-native id — a `GHSA-…` for both v1 sources (npm's numeric id is folded away when a
    /// GHSA is recoverable).
    pub id: String,
    /// Cross-reference ids (`GHSA-…`, `CVE-…`) used to recognize the same vulnerability across
    /// sources — the key [`dedup_advisories`] joins on.
    pub aliases: Vec<String>,
    /// The package name this advisory concerns.
    pub package: String,
    /// The affected version range, as a string the npm/[`Range`] grammar accepts — npm's raw
    /// `vulnerable_versions`, or a `>=`/`<` range synthesized from OSV's structured events.
    pub vulnerable_range: String,
    /// Normalized severity, when the source provides one.
    pub severity: Option<Severity>,
    /// Short human title / summary.
    pub title: String,
    /// A canonical advisory URL, when known.
    pub url: Option<String>,
    /// CWE identifiers (`CWE-79`, …).
    pub cwe: Vec<String>,
    /// CVSS base score, when the source provides a numeric one (npm does; OSV usually doesn't).
    pub cvss_score: Option<f64>,
    /// CVSS vector string, when present.
    pub cvss_vector: Option<String>,
    /// The installed version this advisory was matched against — set by [`build_report`]; empty
    /// until then.
    pub matched_version: String,
}

/// Per-severity advisory counts — the shape of npm's `metadata.vulnerabilities`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Vulnerabilities {
    pub info: u64,
    pub low: u64,
    pub moderate: u64,
    pub high: u64,
    pub critical: u64,
    pub total: u64,
}

/// One vulnerable installed component and the advisories that hit its exact version.
#[derive(Debug, Clone)]
pub struct ComponentAdvisories {
    pub component: Component,
    pub advisories: Vec<Advisory>,
}

/// The result of an audit: the vulnerable components (sorted by name then version), the per-severity
/// totals across them, the names of any advisory sources that could not be reached, and the
/// dependencies the component loading could not audit — so a caller can tell an incomplete run
/// from a genuinely clean one.
#[derive(Debug, Clone)]
pub struct AuditReport {
    pub findings: Vec<ComponentAdvisories>,
    pub vulnerabilities: Vulnerabilities,
    /// Advisory sources whose lookup failed; empty when every selected source answered.
    pub failed_sources: Vec<String>,
    /// Dependencies the audited component set does **not** cover (manifest/spec sources only —
    /// non-registry specs, workspaces, failed optional deps; always empty for a lockfile audit).
    /// Distinct from [`failed_sources`](Self::failed_sources): these are inputs never checked,
    /// not advisory databases that failed. [`run_audit`] leaves this empty; the caller that
    /// loaded the components fills it in.
    pub omissions: Vec<crate::registry::Omission>,
}

impl AuditReport {
    /// The highest severity present across all findings, if any.
    pub fn max_severity(&self) -> Option<Severity> {
        self.advisories().filter_map(|a| a.severity).max()
    }

    /// Whether the audit reached every selected source *and* covered every dependency. `false`
    /// means the report may be missing advisories (see
    /// [`failed_sources`](Self::failed_sources) and [`omissions`](Self::omissions)).
    pub fn is_complete(&self) -> bool {
        self.failed_sources.is_empty() && self.omissions.is_empty()
    }

    /// Whether any finding is at or above `level` — the `--audit-level` exit test. A confirmed
    /// finding whose severity could not be determined (`None`) counts as exceeding *any* level: the
    /// vulnerability is confirmed to affect the installed version, so an unknown severity keeps it
    /// actionable rather than letting it pass silently.
    pub fn exceeds(&self, level: Severity) -> bool {
        self.advisories()
            .any(|a| a.severity.is_none_or(|s| s >= level))
    }

    fn advisories(&self) -> impl Iterator<Item = &Advisory> {
        self.findings.iter().flat_map(|f| f.advisories.iter())
    }
}

/// An advisory database that can be queried for the vulnerabilities affecting a set of components.
///
/// An implementation returns `Ok(advisories)` when the source answered (an empty vector means "no
/// advisories"), and `Err` when the source could **not** be reached — an unreachable endpoint, a
/// network error, or an unusable response. [`run_audit`] records those failures in
/// [`AuditReport::failed_sources`] so a caller can distinguish an incomplete audit from a clean one;
/// a single failing source still never sinks the run.
pub trait AdvisorySource {
    /// A short, stable name (`"npm"`, `"osv"`, …) used in [`Advisory::source`] and diagnostics.
    fn name(&self) -> &'static str;
    /// Query advisories affecting `components`. `Err` means the source was unreachable, not that
    /// there were no advisories.
    fn query(&self, components: &[Component]) -> crate::Result<Vec<Advisory>>;
}

/// Query every source, then dedup across sources and keep only advisories that actually apply to an
/// installed version ([`build_report`]). A source that fails is reported to stderr, recorded in the
/// report's [`failed_sources`](AuditReport::failed_sources), and skipped — a single failing source
/// never sinks the run, but the report is marked incomplete so the caller need not present it as clean.
/// This is `run_audit_observed` (the crate-internal eventful variant) with a no-op observer.
pub fn run_audit(components: &[Component], sources: &[Box<dyn AdvisorySource>]) -> AuditReport {
    run_audit_observed(components, sources, |_| {})
}

/// A progress event from [`run_audit_observed`]'s per-source loop, in emission order: `Begin`
/// fires immediately before a source is queried (naming it), then exactly one of `Done` (with
/// the number of advisories that source returned, before cross-source dedup and
/// installed-version filtering) or `Failed` — so the source a `Done`/`Failed` concerns is the
/// one the preceding `Begin` named. The CLI renders these as stderr status lines; [`run_audit`]
/// discards them. The data fields are read only by that feature-gated renderer, hence the
/// library-only `allow(dead_code)`.
pub(crate) enum SourceEvent<'a> {
    Begin {
        #[cfg_attr(not(feature = "cli"), allow(dead_code))]
        name: &'a str,
    },
    Done {
        #[cfg_attr(not(feature = "cli"), allow(dead_code))]
        advisories: usize,
    },
    Failed,
}

/// [`run_audit`] with a progress observer — the same querying, failure recording, dedup, and
/// report building; `on_event` additionally sees one [`SourceEvent::Begin`] and one `Done`/`Failed`
/// per source, in order. `Failed` fires before the stderr cause line, so a status renderer can
/// close its line first. The returned [`AuditReport`] is identical to [`run_audit`]'s.
pub(crate) fn run_audit_observed(
    components: &[Component],
    sources: &[Box<dyn AdvisorySource>],
    mut on_event: impl FnMut(SourceEvent<'_>),
) -> AuditReport {
    let mut all = Vec::new();
    let mut failed_sources = Vec::new();
    for source in sources {
        on_event(SourceEvent::Begin {
            name: source.name(),
        });
        match source.query(components) {
            Ok(advisories) => {
                on_event(SourceEvent::Done {
                    advisories: advisories.len(),
                });
                all.extend(advisories);
            }
            Err(e) => {
                on_event(SourceEvent::Failed);
                crate::warn::warn(&format!(
                    "{} advisory source failed: {e}; audit results may be incomplete",
                    source.name()
                ));
                failed_sources.push(source.name().to_string());
            }
        }
    }
    let deduped = dedup_advisories(all);
    let mut report = build_report(&deduped, components);
    report.failed_sources = failed_sources;
    report
}

/// The normalized GHSA-/CVE-shaped identity tokens of an advisory (its `id` plus `aliases`),
/// uppercased. A purely numeric npm id is not a stable cross-source key, so it is excluded.
fn advisory_keys(adv: &Advisory) -> Vec<String> {
    std::iter::once(&adv.id)
        .chain(adv.aliases.iter())
        .map(|s| s.trim().to_ascii_uppercase())
        .filter(|k| k.starts_with("GHSA-") || k.starts_with("CVE-"))
        .collect()
}

/// Collapse advisories that describe the same vulnerability for the same package across sources,
/// joined by any shared `GHSA-`/`CVE-` token. The first occurrence wins (sources are concatenated in
/// selection order, npm before osv), and a later duplicate's aliases / url / cwe / cvss / severity
/// enrich the survivor where it lacks them — so an OSV record's CVE alias decorates the npm GHSA.
pub fn dedup_advisories(advisories: Vec<Advisory>) -> Vec<Advisory> {
    let mut out: Vec<Advisory> = Vec::new();
    for adv in advisories {
        let keys = advisory_keys(&adv);
        let existing = out.iter_mut().find(|e| {
            e.package == adv.package && advisory_keys(e).iter().any(|k| keys.contains(k))
        });
        match existing {
            Some(into) => merge_advisory(into, adv),
            None => out.push(adv),
        }
    }
    out
}

/// Fold `from` into `into`: union the alias sets (adding `from`'s native id when it is a GHSA/CVE),
/// and fill any field `into` is missing.
fn merge_advisory(into: &mut Advisory, from: Advisory) {
    let add_alias = |into: &mut Advisory, alias: String| {
        let k = alias.trim().to_ascii_uppercase();
        if !into
            .aliases
            .iter()
            .any(|x| x.trim().to_ascii_uppercase() == k)
            && into.id != alias
        {
            into.aliases.push(alias);
        }
    };
    let from_id_upper = from.id.trim().to_ascii_uppercase();
    if from_id_upper.starts_with("GHSA-") || from_id_upper.starts_with("CVE-") {
        add_alias(into, from.id);
    }
    for a in from.aliases {
        add_alias(into, a);
    }
    if into.url.is_none() {
        into.url = from.url;
    }
    if into.cwe.is_empty() {
        into.cwe = from.cwe;
    }
    if into.cvss_score.is_none() {
        into.cvss_score = from.cvss_score;
    }
    if into.cvss_vector.is_none() {
        into.cvss_vector = from.cvss_vector;
    }
    if into.severity.is_none() {
        into.severity = from.severity;
    }
}

/// Match deduped advisories against the installed components and group the hits into an
/// [`AuditReport`].
///
/// A component is a finding when an advisory for its name has a `vulnerable_range` that contains its
/// exact installed version (`Range::matches`) — the guard against the npm endpoint over-broadening
/// ranges and against OSV's multi-package records. Components are de-duplicated by `name@version`
/// first (a lockfile can pin one version at several tree paths), and each stored advisory records
/// the `matched_version` it applied to. A component whose version or an advisory's range won't parse
/// is skipped rather than reported.
pub fn build_report(advisories: &[Advisory], components: &[Component]) -> AuditReport {
    let mut by_name: BTreeMap<&str, Vec<&Advisory>> = BTreeMap::new();
    for a in advisories {
        by_name.entry(a.package.as_str()).or_default().push(a);
    }

    let mut seen: BTreeSet<(&str, &str)> = BTreeSet::new();
    let mut findings = Vec::new();
    let mut counts = Vulnerabilities::default();
    for c in components {
        if !seen.insert((c.name.as_str(), c.version.as_str())) {
            continue; // same name@version already considered (duplicate tree path)
        }
        let Ok(version) = Version::parse(&c.version) else {
            continue;
        };
        let Some(candidates) = by_name.get(c.name.as_str()) else {
            continue;
        };
        let mut hits = Vec::new();
        for adv in candidates {
            // An empty range parses as "any" and would match every installed version; never
            // over-report on a missing range — skip the advisory instead.
            if adv.vulnerable_range.trim().is_empty() {
                continue;
            }
            let Ok(range) = Range::parse(&adv.vulnerable_range) else {
                continue;
            };
            if range.matches(&version) {
                let mut hit = (*adv).clone();
                hit.matched_version = c.version.clone();
                count_one(&mut counts, hit.severity);
                hits.push(hit);
            }
        }
        if !hits.is_empty() {
            findings.push(ComponentAdvisories {
                component: c.clone(),
                advisories: hits,
            });
        }
    }
    AuditReport {
        findings,
        vulnerabilities: counts,
        failed_sources: Vec::new(),
        omissions: Vec::new(),
    }
}

fn count_one(v: &mut Vulnerabilities, severity: Option<Severity>) {
    match severity {
        Some(Severity::Low) => v.low += 1,
        Some(Severity::Moderate) => v.moderate += 1,
        Some(Severity::High) => v.high += 1,
        Some(Severity::Critical) => v.critical += 1,
        None => v.info += 1,
    }
    v.total += 1;
}

/// The reason an audit is incomplete, for `AUDIT INCOMPLETE` renderings: failed advisory
/// sources, unaudited dependencies, or both. `None` when the audit covered everything.
fn incomplete_clause(report: &AuditReport) -> Option<String> {
    let mut parts = Vec::new();
    if !report.failed_sources.is_empty() {
        parts.push(format!(
            "{} source(s) failed ({})",
            report.failed_sources.len(),
            report.failed_sources.join(", "),
        ));
    }
    if !report.omissions.is_empty() {
        let n = report.omissions.len();
        parts.push(format!(
            "{n} dependenc{} not audited",
            if n == 1 { "y" } else { "ies" },
        ));
    }
    (!parts.is_empty()).then(|| parts.join(", "))
}

/// The itemized unaudited-dependency note printed above the count header, so a clean count is
/// never unqualified when the component set has gaps.
fn omissions_note(report: &AuditReport) -> Option<String> {
    if report.omissions.is_empty() {
        return None;
    }
    let n = report.omissions.len();
    let items: Vec<String> = report.omissions.iter().map(|o| o.to_string()).collect();
    Some(format!(
        "note: {n} dependenc{} not audited: {}",
        if n == 1 { "y" } else { "ies" },
        items.join(", "),
    ))
}

/// A plain-text audit summary: a one-line count header, then each vulnerable `name@version` with its
/// advisories. `found 0 vulnerabilities` when clean (mirrors `npm audit`). Unaudited dependencies
/// are itemized in a `note:` line above the header and flag the audit `INCOMPLETE`.
pub fn render_summary(report: &AuditReport) -> String {
    use std::fmt::Write as _;
    let v = &report.vulnerabilities;
    let mut s = String::new();
    if let Some(note) = omissions_note(report) {
        let _ = writeln!(s, "{note}");
    }
    if v.total == 0 {
        match incomplete_clause(report) {
            None => s.push_str("found 0 vulnerabilities\n"),
            Some(clause) => {
                let _ = writeln!(s, "found 0 vulnerabilities — AUDIT INCOMPLETE: {clause}");
            }
        }
        return s;
    }
    let mut info = String::new();
    if v.info > 0 {
        let _ = write!(info, ", {} info", v.info);
    }
    let _ = writeln!(
        s,
        "found {} vulnerabilit{} ({} critical, {} high, {} moderate, {} low{info}) in {} package(s)",
        v.total,
        if v.total == 1 { "y" } else { "ies" },
        v.critical,
        v.high,
        v.moderate,
        v.low,
        report.findings.len(),
    );
    for f in &report.findings {
        let _ = write!(s, "\n{}@{}\n", f.component.name, f.component.version);
        for a in &f.advisories {
            let severity = a.severity.map(Severity::as_str).unwrap_or("unknown");
            let _ = writeln!(s, "  {:<8} {}  {}", severity.to_uppercase(), a.id, a.title);
            let mut detail = format!("range {}", a.vulnerable_range);
            if !a.cwe.is_empty() {
                let _ = write!(detail, " · {}", a.cwe.join(", "));
            }
            if let Some(url) = &a.url {
                let _ = write!(detail, " · {url}");
            }
            let _ = writeln!(s, "    {detail}");
        }
    }
    if let Some(clause) = incomplete_clause(report) {
        let _ = writeln!(s, "\nAUDIT INCOMPLETE: {clause} — findings may be missing");
    }
    s
}

/// An `npm audit --json`-shaped report: a `vulnerabilities` object keyed by package name (each with
/// its affected installed `versions`, the max `severity`, and the advisories under `via`) plus a
/// `metadata.vulnerabilities` per-severity count block.
pub fn render_json(report: &AuditReport) -> String {
    // Group component findings by name — a name can be installed at several versions.
    let mut by_name: BTreeMap<&str, Vec<&ComponentAdvisories>> = BTreeMap::new();
    for f in &report.findings {
        by_name
            .entry(f.component.name.as_str())
            .or_default()
            .push(f);
    }

    let mut vulns = Map::new();
    for (name, group) in &by_name {
        let mut versions: Vec<&str> = group.iter().map(|f| f.component.version.as_str()).collect();
        versions.sort_unstable();
        versions.dedup();
        let max = group
            .iter()
            .flat_map(|f| f.advisories.iter())
            .filter_map(|a| a.severity)
            .max();
        let via: Vec<Value> = group
            .iter()
            .flat_map(|f| f.advisories.iter())
            .map(advisory_json)
            .collect();
        vulns.insert(
            (*name).to_string(),
            json!({
                "name": name,
                "severity": max.map(Severity::as_str).unwrap_or("unknown"),
                "versions": versions,
                "via": via,
            }),
        );
    }

    let v = &report.vulnerabilities;
    let doc = json!({
        "vulnerabilities": Value::Object(vulns),
        "metadata": {
            "vulnerabilities": {
                "info": v.info,
                "low": v.low,
                "moderate": v.moderate,
                "high": v.high,
                "critical": v.critical,
                "total": v.total,
            },
        },
        // Extensions beyond `npm audit --json` so a machine can distinguish an incomplete audit
        // from a clean one: `incomplete` is true when any source failed or any dependency went
        // unaudited; `failed_sources` and `omissions` say which.
        "incomplete": !report.is_complete(),
        "failed_sources": report.failed_sources,
        "omissions": report.omissions.iter().map(|o| json!({
            "name": o.name,
            "spec": o.spec,
            "reason": o.reason,
        })).collect::<Vec<Value>>(),
    });
    let mut s = serde_json::to_string_pretty(&doc).expect("serialize audit report");
    s.push('\n');
    s
}

fn advisory_json(a: &Advisory) -> Value {
    let mut m = Map::new();
    m.insert("source".into(), json!(a.source));
    m.insert("id".into(), json!(a.id));
    if !a.aliases.is_empty() {
        m.insert("aliases".into(), json!(a.aliases));
    }
    m.insert("title".into(), json!(a.title));
    m.insert("vulnerable_range".into(), json!(a.vulnerable_range));
    if !a.matched_version.is_empty() {
        m.insert("matched_version".into(), json!(a.matched_version));
    }
    if let Some(s) = a.severity {
        m.insert("severity".into(), json!(s.as_str()));
    }
    if let Some(u) = &a.url {
        m.insert("url".into(), json!(u));
    }
    if !a.cwe.is_empty() {
        m.insert("cwe".into(), json!(a.cwe));
    }
    if let Some(score) = a.cvss_score {
        m.insert("cvss_score".into(), json!(score));
    }
    if let Some(vector) = &a.cvss_vector {
        m.insert("cvss_vector".into(), json!(vector));
    }
    Value::Object(m)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn advisory(
        source: &'static str,
        id: &str,
        aliases: &[&str],
        range: &str,
        sev: Option<Severity>,
    ) -> Advisory {
        Advisory {
            source,
            id: id.into(),
            aliases: aliases.iter().map(|s| s.to_string()).collect(),
            package: "lodash".into(),
            vulnerable_range: range.into(),
            severity: sev,
            title: format!("advisory {id}"),
            url: None,
            cwe: vec![],
            cvss_score: None,
            cvss_vector: None,
            matched_version: String::new(),
        }
    }

    fn component(name: &str, version: &str) -> Component {
        Component {
            name: name.into(),
            version: version.into(),
            purl: format!("pkg:npm/{name}@{version}"),
            license: None,
            resolved: None,
            integrity: None,
        }
    }

    /// Fake sources for the observed-loop test: one succeeds with `usize` advisories, one fails.
    struct OkSource(&'static str, usize);
    impl AdvisorySource for OkSource {
        fn name(&self) -> &'static str {
            self.0
        }
        fn query(&self, _: &[Component]) -> crate::Result<Vec<Advisory>> {
            Ok((0..self.1)
                .map(|i| advisory("fake", &format!("GHSA-ok-{i}"), &[], "<9", None))
                .collect())
        }
    }
    struct BadSource;
    impl AdvisorySource for BadSource {
        fn name(&self) -> &'static str {
            "bad"
        }
        fn query(&self, _: &[Component]) -> crate::Result<Vec<Advisory>> {
            Err("simulated outage".into())
        }
    }

    #[test]
    fn run_audit_observed_emits_begin_done_failed_in_order() {
        let sources: Vec<Box<dyn AdvisorySource>> =
            vec![Box::new(OkSource("ok", 2)), Box::new(BadSource)];
        let components = [component("lodash", "4.17.20")];

        let mut events: Vec<String> = Vec::new();
        let observed = run_audit_observed(&components, &sources, |e| {
            events.push(match e {
                SourceEvent::Begin { name } => format!("begin {name}"),
                SourceEvent::Done { advisories } => format!("done {advisories}"),
                SourceEvent::Failed => "failed".to_string(),
            });
        });

        // A `Done`/`Failed` concerns the source the preceding `Begin` named.
        assert_eq!(events, ["begin ok", "done 2", "begin bad", "failed"]);
        assert_eq!(observed.failed_sources, ["bad".to_string()]);

        // The observer changes nothing about the report itself.
        let plain = run_audit(&components, &sources);
        assert_eq!(observed.vulnerabilities.total, plain.vulnerabilities.total);
        assert_eq!(observed.failed_sources, plain.failed_sources);
    }

    #[test]
    fn severity_buckets_from_cvss() {
        assert_eq!(severity_from_cvss(0.0), None);
        assert_eq!(severity_from_cvss(3.9), Some(Severity::Low));
        assert_eq!(severity_from_cvss(6.9), Some(Severity::Moderate));
        assert_eq!(severity_from_cvss(7.2), Some(Severity::High));
        assert_eq!(severity_from_cvss(9.8), Some(Severity::Critical));
        assert!(Severity::Low < Severity::Critical);
        assert_eq!(
            Severity::from_str_loose("CRITICAL"),
            Some(Severity::Critical)
        );
        assert_eq!(Severity::from_str_loose("medium"), Some(Severity::Moderate));
        assert_eq!(Severity::from_str_loose("info"), None);
    }

    #[test]
    fn dedup_joins_on_shared_alias_and_enriches() {
        let npm = advisory(
            "npm",
            "GHSA-aaaa-bbbb-cccc",
            &["GHSA-aaaa-bbbb-cccc"],
            "<2.0.0",
            Some(Severity::High),
        );
        let mut osv = advisory(
            "osv",
            "GHSA-aaaa-bbbb-cccc",
            &["GHSA-aaaa-bbbb-cccc", "CVE-2021-1"],
            "<2.0.0",
            Some(Severity::High),
        );
        osv.url = Some("https://osv.dev/x".into());
        osv.cwe = vec!["CWE-79".into()];

        let out = dedup_advisories(vec![npm, osv]);
        assert_eq!(out.len(), 1, "the two sources collapse to one advisory");
        assert_eq!(out[0].source, "npm", "first occurrence wins");
        assert!(
            out[0].aliases.iter().any(|a| a == "CVE-2021-1"),
            "CVE alias merged in from osv"
        );
        assert_eq!(
            out[0].url.as_deref(),
            Some("https://osv.dev/x"),
            "url enriched"
        );
        assert_eq!(out[0].cwe, vec!["CWE-79"], "cwe enriched");

        // A different CVE for the same package does NOT collapse.
        let a = advisory("npm", "GHSA-1", &["CVE-1"], "<2.0.0", Some(Severity::Low));
        let b = advisory("osv", "GHSA-2", &["CVE-2"], "<2.0.0", Some(Severity::Low));
        assert_eq!(dedup_advisories(vec![a, b]).len(), 2);
    }

    #[test]
    fn build_report_keeps_only_in_range_installs_and_counts() {
        let advisories = vec![
            advisory(
                "npm",
                "GHSA-old",
                &["GHSA-old"],
                "<4.17.21",
                Some(Severity::High),
            ),
            advisory(
                "npm",
                "GHSA-wide",
                &["GHSA-wide"],
                "<=4.17.23",
                Some(Severity::Moderate),
            ),
        ];
        // 4.17.20 is below both ceilings → two findings, counted.
        let r = build_report(&advisories, &[component("lodash", "4.17.20")]);
        assert_eq!(r.vulnerabilities.total, 2);
        assert_eq!(r.vulnerabilities.high, 1);
        assert_eq!(r.vulnerabilities.moderate, 1);
        assert_eq!(r.findings[0].advisories[0].matched_version, "4.17.20");

        // 4.17.22 clears the <4.17.21 one but is still <=4.17.23.
        let r = build_report(&advisories, &[component("lodash", "4.17.22")]);
        assert_eq!(r.vulnerabilities.total, 1);
        assert!(r.findings[0].advisories.iter().all(|a| a.id == "GHSA-wide"));

        // A package the advisories don't mention is clean; an unparsable version is skipped.
        assert_eq!(
            build_report(&advisories, &[component("left-pad", "1.3.0")])
                .vulnerabilities
                .total,
            0
        );
        assert_eq!(
            build_report(&advisories, &[component("lodash", "not-semver")])
                .vulnerabilities
                .total,
            0
        );
    }

    #[test]
    fn build_report_dedups_same_name_version_across_tree_paths() {
        let advisories = vec![advisory(
            "npm",
            "GHSA-x",
            &["GHSA-x"],
            "<2.0.0",
            Some(Severity::Low),
        )];
        // The same lodash@1.0.0 pinned at two paths must not double-count.
        let r = build_report(
            &advisories,
            &[component("lodash", "1.0.0"), component("lodash", "1.0.0")],
        );
        assert_eq!(r.vulnerabilities.total, 1);
        assert_eq!(r.findings.len(), 1);
    }

    #[test]
    fn exceeds_respects_threshold_and_renders() {
        let advisories = vec![advisory(
            "npm",
            "GHSA-h",
            &["GHSA-h"],
            "<2.0.0",
            Some(Severity::High),
        )];
        let report = build_report(&advisories, &[component("lodash", "1.0.0")]);
        assert!(report.exceeds(Severity::Low));
        assert!(report.exceeds(Severity::High));
        assert!(!report.exceeds(Severity::Critical));
        assert_eq!(report.max_severity(), Some(Severity::High));

        assert!(render_summary(&report).contains("found 1 vulnerability"));
        assert!(render_summary(&report).contains("lodash@1.0.0"));
        let empty = AuditReport {
            findings: vec![],
            vulnerabilities: Vulnerabilities::default(),
            failed_sources: vec![],
            omissions: vec![],
        };
        assert_eq!(render_summary(&empty), "found 0 vulnerabilities\n");

        // JSON shape: keyed by name, with a metadata count block.
        let doc: Value = serde_json::from_str(&render_json(&report)).unwrap();
        assert_eq!(doc["vulnerabilities"]["lodash"]["severity"], "high");
        assert_eq!(doc["metadata"]["vulnerabilities"]["high"], 1);
        assert_eq!(doc["metadata"]["vulnerabilities"]["total"], 1);
        assert_eq!(doc["incomplete"], false);
        assert_eq!(
            doc["omissions"],
            json!([]),
            "always present, empty by default"
        );
    }

    #[test]
    fn omissions_qualify_a_clean_summary_and_mark_it_incomplete() {
        let report = AuditReport {
            findings: vec![],
            vulnerabilities: Vulnerabilities::default(),
            failed_sources: vec![],
            omissions: vec![crate::registry::Omission::new(
                "g",
                "git+ssh://x/y",
                "git dependency",
            )],
        };
        assert!(!report.is_complete());
        let s = render_summary(&report);
        assert_eq!(
            s,
            "note: 1 dependency not audited: g (git+ssh://x/y: git dependency)\n\
             found 0 vulnerabilities — AUDIT INCOMPLETE: 1 dependency not audited\n"
        );
    }

    #[test]
    fn omissions_and_failed_sources_compose_in_summary_and_json() {
        let advisories = vec![advisory(
            "npm",
            "GHSA-h",
            &["GHSA-h"],
            "<2.0.0",
            Some(Severity::High),
        )];
        let mut report = build_report(&advisories, &[component("lodash", "1.0.0")]);
        report.failed_sources = vec!["osv".into()];
        report.omissions = vec![
            crate::registry::Omission::new("w", "file:../w", "local path"),
            crate::registry::Omission::new("workspaces", "", "not traversed"),
        ];

        let s = render_summary(&report);
        // The note leads, the count header follows intact, the trailing block names both gaps.
        let note_pos = s.find("note: 2 dependencies not audited:").unwrap();
        let found_pos = s.find("found 1 vulnerability").unwrap();
        assert!(note_pos < found_pos, "{s}");
        assert!(
            s.contains(
                "AUDIT INCOMPLETE: 1 source(s) failed (osv), 2 dependencies not audited \
                 — findings may be missing"
            ),
            "{s}"
        );

        let doc: Value = serde_json::from_str(&render_json(&report)).unwrap();
        assert_eq!(doc["incomplete"], true);
        assert_eq!(doc["omissions"][0]["name"], "w");
        assert_eq!(doc["omissions"][0]["reason"], "local path");
        assert_eq!(doc["omissions"][1]["spec"], "");
    }
}