Skip to main content

openmoat_core/
packages.rs

1//! Package names, and whether one is a near miss of a popular package (ADR-030).
2//!
3//! Each registry has a bundled list of its most-installed names
4//! (`data/top-packages/<ecosystem>.txt`), and `npm` and `PyPI` one of the tools
5//! people run with a package runner (`<ecosystem>-tools.txt`, ADR-102).
6//! Nothing is looked up online. A name that is not on its lists but is one
7//! typo or a common trick away from a name that is (`reqeusts` for
8//! `requests`, `lodahs` for `lodash`, `python-redis` for `redis`) is a near
9//! miss: what a typo-squat or a package name an agent made up looks like. For
10//! an install every other name, unknown ones included, is normal; a runner
11//! that fetches and runs a name not on the lists needs review
12//! (`package-run-unknown`), so for runners the lists are an allowlist.
13
14use std::collections::HashSet;
15use std::sync::LazyLock;
16
17/// A package registry whose installs the shell classifier recognises.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Ecosystem {
20    /// The npm registry (`npm`, `pnpm`, `yarn`, `bun`).
21    Npm,
22    /// The Python Package Index (`pip`, `uv`, `poetry`, `pipx`).
23    Pypi,
24    /// crates.io (`cargo add`, `cargo install`).
25    Crates,
26    /// rubygems.org (`gem install`).
27    Rubygems,
28    /// Go modules (`go get`, `go install`).
29    Go,
30}
31
32/// Names shorter than this (after normalising) are never near misses: among
33/// short names one letter is the whole difference between two real packages.
34const MIN_LEN: usize = 5;
35
36impl Ecosystem {
37    /// The id used in atoms and reasons.
38    #[must_use]
39    pub fn id(self) -> &'static str {
40        match self {
41            Self::Npm => "npm",
42            Self::Pypi => "pypi",
43            Self::Crates => "crates",
44            Self::Rubygems => "rubygems",
45            Self::Go => "go",
46        }
47    }
48
49    fn index(self) -> usize {
50        match self {
51            Self::Npm => 0,
52            Self::Pypi => 1,
53            Self::Crates => 2,
54            Self::Rubygems => 3,
55            Self::Go => 4,
56        }
57    }
58
59    /// The ecosystem whose [`Self::id`] is `id`.
60    #[must_use]
61    pub fn from_id(id: &str) -> Option<Self> {
62        [
63            Self::Npm,
64            Self::Pypi,
65            Self::Crates,
66            Self::Rubygems,
67            Self::Go,
68        ]
69        .into_iter()
70        .find(|e| e.id() == id)
71    }
72
73    /// The bundled lists: the most-installed names, then the tools commonly
74    /// run with a package runner (`*-tools.txt`, kept by hand, ADR-102).
75    fn lists(self) -> [&'static str; 2] {
76        match self {
77            Self::Npm => [
78                include_str!("../data/top-packages/npm.txt"),
79                include_str!("../data/top-packages/npm-tools.txt"),
80            ],
81            Self::Pypi => [
82                include_str!("../data/top-packages/pypi.txt"),
83                include_str!("../data/top-packages/pypi-tools.txt"),
84            ],
85            Self::Crates => [include_str!("../data/top-packages/crates.txt"), ""],
86            Self::Rubygems => [include_str!("../data/top-packages/rubygems.txt"), ""],
87            Self::Go => [include_str!("../data/top-packages/go.txt"), ""],
88        }
89    }
90
91    /// Words squatters put before and after a popular name (`node-`, `-js`,
92    /// `python-`, `-rs`), in normalised form.
93    fn affixes(self) -> (&'static [&'static str], &'static [&'static str]) {
94        match self {
95            Self::Npm => (
96                &["node-", "nodejs-", "js-"],
97                &["-js", ".js", "js", "-node", "-nodejs"],
98            ),
99            Self::Pypi => (&["python-", "python3-", "py-", "py"], &["-python", "-py"]),
100            Self::Crates => (&["rust-", "rs-"], &["-rs", "-rust"]),
101            Self::Rubygems => (&["ruby-"], &["-ruby", "-rb", ".rb"]),
102            Self::Go => (&[], &[]),
103        }
104    }
105
106    /// The name as the registry compares names: the Python index folds case and treats
107    /// runs of `-`, `_` and `.` as one `-` (PEP 503); crates.io folds case and
108    /// `_` into `-`; a Go module's major version suffix (`/v2`) is dropped.
109    #[must_use]
110    pub fn normalise(self, name: &str) -> String {
111        let lower = name.to_ascii_lowercase();
112        match self {
113            Self::Pypi => {
114                let mut out = String::with_capacity(lower.len());
115                for c in lower.chars() {
116                    if matches!(c, '-' | '_' | '.') {
117                        if !out.ends_with('-') {
118                            out.push('-');
119                        }
120                    } else {
121                        out.push(c);
122                    }
123                }
124                out
125            }
126            Self::Crates => lower.replace('_', "-"),
127            Self::Go => match lower.rsplit_once("/v") {
128                Some((module, major))
129                    if !major.is_empty() && major.bytes().all(|b| b.is_ascii_digit()) =>
130                {
131                    module.to_owned()
132                }
133                _ => lower,
134            },
135            Self::Npm | Self::Rubygems => lower,
136        }
137    }
138}
139
140/// One ecosystem's list: names in popularity order, normalised and as written.
141struct Top {
142    names: Vec<(String, &'static str)>,
143    known: HashSet<String>,
144}
145
146impl Top {
147    fn load(ecosystem: Ecosystem) -> Self {
148        let names: Vec<(String, &'static str)> = ecosystem
149            .lists()
150            .into_iter()
151            .flat_map(str::lines)
152            .map(str::trim)
153            .filter(|l| !l.is_empty() && !l.starts_with('#'))
154            .map(|l| (ecosystem.normalise(l), l))
155            .collect();
156        let known = names.iter().map(|(n, _)| n.clone()).collect();
157        Self { names, known }
158    }
159}
160
161static TOP: LazyLock<[Top; 5]> = LazyLock::new(|| {
162    [
163        Ecosystem::Npm,
164        Ecosystem::Pypi,
165        Ecosystem::Crates,
166        Ecosystem::Rubygems,
167        Ecosystem::Go,
168    ]
169    .map(Top::load)
170});
171
172/// How many names the bundled list of `ecosystem` holds.
173#[cfg(test)]
174fn list_len(ecosystem: Ecosystem) -> usize {
175    TOP[ecosystem.index()].names.len()
176}
177
178/// The popular package `name` is a near miss of, if it is one: `name` is not
179/// on the list, and a listed name of at least five characters is one edit
180/// away (a letter added, dropped, changed or two swapped), differs only in
181/// `-`, `_` and `.` or in doubled letters, or is `name` with a squatter's
182/// prefix or suffix added or removed. The most popular such name is returned.
183#[must_use]
184pub fn near_miss(ecosystem: Ecosystem, name: &str) -> Option<&'static str> {
185    let top = &TOP[ecosystem.index()];
186    let key = ecosystem.normalise(name);
187    if !key.is_ascii() || top.known.contains(&key) {
188        return None;
189    }
190    let (prefixes, suffixes) = ecosystem.affixes();
191    let stripped = without_separators(&key);
192    let collapsed = collapse_runs(&key);
193    top.names
194        .iter()
195        .filter(|(popular, _)| popular.len() >= MIN_LEN)
196        .find(|(popular, _)| {
197            (stripped.len() >= MIN_LEN && stripped == without_separators(popular))
198                || (collapsed.len() >= MIN_LEN && collapsed == collapse_runs(popular))
199                || one_edit(&key, popular)
200                || affixed(&key, popular, prefixes, suffixes)
201                || (key.len() >= MIN_LEN && affixed(popular, &key, prefixes, suffixes))
202        })
203        .map(|(_, written)| *written)
204}
205
206/// Whether `name` is on the bundled list of `ecosystem`'s popular packages,
207/// compared as the registry compares names.
208#[must_use]
209pub fn is_popular(ecosystem: Ecosystem, name: &str) -> bool {
210    TOP[ecosystem.index()]
211        .known
212        .contains(&ecosystem.normalise(name))
213}
214
215fn without_separators(name: &str) -> String {
216    name.chars()
217        .filter(|c| !matches!(c, '-' | '_' | '.'))
218        .collect()
219}
220
221/// `name` with each run of one character kept once (`expresss` → `expres`).
222fn collapse_runs(name: &str) -> String {
223    let mut out = String::with_capacity(name.len());
224    for c in name.chars() {
225        if !out.ends_with(c) {
226            out.push(c);
227        }
228    }
229    out
230}
231
232/// Whether `long` is `base` with one of the prefixes or suffixes added.
233fn affixed(long: &str, base: &str, prefixes: &[&str], suffixes: &[&str]) -> bool {
234    prefixes
235        .iter()
236        .any(|p| long.strip_prefix(p).is_some_and(|rest| rest == base))
237        || suffixes
238            .iter()
239            .any(|s| long.strip_suffix(s).is_some_and(|rest| rest == base))
240}
241
242/// Whether `a` and `b` differ by exactly one insertion, deletion, substitution
243/// or swap of two neighbouring characters (optimal string alignment distance 1).
244fn one_edit(a: &str, b: &str) -> bool {
245    let (a, b) = (a.as_bytes(), b.as_bytes());
246    if a == b || a.len().abs_diff(b.len()) > 1 {
247        return false;
248    }
249    let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
250    let (a, b) = (&a[prefix..], &b[prefix..]);
251    match (a.len(), b.len()) {
252        (n, m) if n == m => {
253            // one substitution, or one swap of neighbours
254            a[1..] == b[1..] || (n >= 2 && a[0] == b[1] && a[1] == b[0] && a[2..] == b[2..])
255        }
256        (n, m) if n > m => a[1..] == *b,
257        _ => *a == b[1..],
258    }
259}
260
261#[cfg(test)]
262mod tests;