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
//! npm source: full version history, deprecation state, and tarball metadata.
//!
//! The packument at `https://registry.npmjs.org/{name}` lists every published
//! version, including pre-releases. Scoped names are percent-encoded for the
//! path lookup while the display name reported by the payload is preserved in
//! project metadata. npm publishes only SHA-1 (`dist.shasum`) and SHA-512
//! (`dist.integrity`) digests, so the artifact SHA-256 stays unknown until the
//! resolver downloads the tarball; neither digest is ever relabeled. The
//! packument does not report tarball bytes, so `dist.unpackedSize` is carried
//! as the size fallback and the resolver records the real size after download.
use std::sync::Arc;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use serde_json::{Map, Value};
use crate::release::http::RegistryHttp;
use crate::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};
use crate::release::versioning::{VersionScheme, compare, normalize_version};
pub const REGISTRY_BASE: &str = "https://registry.npmjs.org";
/// npm path encoding: `@` stays literal (the registry's scoped-name
/// convention) and the `/` between scope and name becomes `%2F`.
const NPM_PATH: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~')
.remove(b'@');
pub struct NpmSource {
http: Arc<dyn RegistryHttp>,
}
impl NpmSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self { http }
}
/// Registry lookup URL; scoped names become `@scope%2Fname`.
pub fn registry_url(name: &str) -> String {
format!("{REGISTRY_BASE}/{}", utf8_percent_encode(name, NPM_PATH))
}
async fn packument(&self, project: &ProjectRef) -> Result<Value> {
self.http.get_json(&Self::registry_url(&project.name)).await
}
}
#[async_trait]
impl ReleaseSource for NpmSource {
fn name(&self) -> &'static str {
"npm"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: true,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
version_infos(&self.packument(project).await?)
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
Ok(artifacts_for(&self.packument(project).await?, &version.raw))
}
async fn statuses(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
Ok(statuses_for(&self.packument(project).await?, &version.raw))
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
Ok(project_meta_value(
&self.packument(project).await?,
&project.name,
))
}
}
fn version_entry<'a>(payload: &'a Value, raw: &str) -> Option<&'a Value> {
payload.get("versions")?.as_object()?.get(raw)
}
fn version_infos(payload: &Value) -> Result<Vec<VersionInfo>> {
let versions = payload
.get("versions")
.and_then(Value::as_object)
.ok_or_else(|| anyhow!("npm packument missing versions"))?;
let mut infos = versions
.iter()
.map(|(raw, entry)| {
let reason = deprecation_message(entry);
VersionInfo {
raw: raw.clone(),
version: normalize_version(raw).unwrap_or_else(|| raw.clone()),
deprecated: reason.is_some(),
reason: reason.unwrap_or_default(),
}
})
.collect::<Vec<_>>();
infos.sort_by(|left, right| {
compare(VersionScheme::Semver, &right.raw, &left.raw).then_with(|| right.raw.cmp(&left.raw))
});
Ok(infos)
}
fn artifacts_for(payload: &Value, raw: &str) -> Vec<ArtifactInfo> {
let Some(dist) = version_entry(payload, raw).and_then(|entry| entry.get("dist")) else {
return Vec::new();
};
let Some(url) = text_field(dist, "tarball") else {
return Vec::new();
};
let path = url.split(['?', '#']).next().unwrap_or(url);
let file_name = path.rsplit('/').next().unwrap_or(path);
let size = dist
.get("unpackedSize")
.and_then(Value::as_u64)
.filter(|size| *size > 0);
vec![ArtifactInfo {
file_name: file_name.to_owned(),
url: url.to_owned(),
// npm publishes SHA-1 (`shasum`) and SHA-512 (`integrity`) only;
// neither is ever relabeled as SHA-256.
sha256: None,
size,
mime_type: Some("application/gzip".to_owned()),
}]
}
fn statuses_for(payload: &Value, raw: &str) -> Vec<StatusInfo> {
let Some(version) = version_entry(payload, raw) else {
return Vec::new();
};
let Some(reason) = deprecation_message(version) else {
return Vec::new();
};
// Registry deprecations are not security verdicts, even when the message
// mentions a vulnerability; the kind is always `registry`.
vec![StatusInfo {
status: "deprecated".to_owned(),
kind: Some("registry".to_owned()),
reason,
}]
}
/// `Some(reason)` when the version is deprecated. npm stores the message as a
/// string; a bare `true` is accepted as a reasonless deprecation.
fn deprecation_message(version: &Value) -> Option<String> {
match version.get("deprecated")? {
Value::String(reason) => (!reason.is_empty()).then(|| reason.clone()),
value if truthy(Some(value)) => Some(String::new()),
_ => None,
}
}
fn project_meta_value(payload: &Value, requested: &str) -> Value {
let mut meta = Map::new();
insert_text(
&mut meta,
"name",
Some(text_field(payload, "name").unwrap_or(requested)),
);
insert_text(&mut meta, "description", text_field(payload, "description"));
insert_text(&mut meta, "homepage", text_field(payload, "homepage"));
insert_text(&mut meta, "repository", repository_url(payload));
insert_text(&mut meta, "license", license_text(payload));
if let Some(channels) = channel_map(payload) {
meta.insert("channels".to_owned(), Value::Object(channels));
}
Value::Object(meta)
}
fn repository_url(payload: &Value) -> Option<&str> {
match payload.get("repository")? {
Value::String(url) => Some(url.as_str()).filter(|url| !url.is_empty()),
repository => text_field(repository, "url"),
}
}
fn license_text(payload: &Value) -> Option<&str> {
match payload.get("license")? {
Value::String(license) => Some(license.as_str()).filter(|license| !license.is_empty()),
license => text_field(license, "type"),
}
}
/// `dist-tags` (`latest`, `next`, `beta`, ...) become version channels.
fn channel_map(payload: &Value) -> Option<Map<String, Value>> {
let tags = payload.get("dist-tags")?.as_object()?;
let channels = tags
.iter()
.filter_map(|(channel, version)| {
version
.as_str()
.filter(|version| !version.is_empty())
.map(|version| (channel.clone(), Value::String(version.to_owned())))
})
.collect::<Map<String, Value>>();
(!channels.is_empty()).then_some(channels)
}
fn truthy(value: Option<&Value>) -> bool {
match value {
Some(Value::Bool(value)) => *value,
Some(Value::String(value)) => !value.is_empty(),
Some(Value::Number(number)) => number.as_f64().is_some_and(|value| value != 0.0),
Some(Value::Array(values)) => !values.is_empty(),
Some(Value::Object(values)) => !values.is_empty(),
Some(Value::Null) | None => false,
}
}
fn text_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
value
.get(key)
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
}
fn insert_text(meta: &mut Map<String, Value>, key: &str, value: Option<&str>) {
if let Some(value) = value.filter(|value| !value.is_empty()) {
meta.insert(key.to_owned(), Value::String(value.to_owned()));
}
}