aube-registry 1.36.0

npm registry HTTP client for Aube
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
use super::body::{check_body_cap, read_body_capped};
use super::cache::packument_full_cache_path;
use super::{
    AUDIT_BODY_CAP, PACKUMENT_FULL_ACCEPT, RegistryClient, check_dist_tag_status,
    dist_tag_root_url, dist_tag_url, parse_full_response,
};
use crate::Error;
use serde::Deserialize;
use std::borrow::Cow;
use std::path::Path;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageSearchResult {
    pub name: String,
    pub version: String,
    pub description: Option<String>,
}

#[derive(Deserialize)]
struct PackageSearchResponse {
    #[serde(default)]
    objects: Vec<PackageSearchObject>,
}

#[derive(Deserialize)]
struct PackageSearchObject {
    package: PackageSearchPackage,
}

#[derive(Deserialize)]
struct PackageSearchPackage {
    name: String,
    #[serde(default)]
    version: String,
    description: Option<String>,
}

impl RegistryClient {
    /// Search package names using npm's lightweight `/-/v1/search` endpoint.
    ///
    /// Scoped queries use their configured registry and scope-specific auth,
    /// so private package completion follows the same `.npmrc` routing as
    /// packument fetches.
    ///
    /// This intentionally bypasses the normal metadata retry loop: callers use
    /// it for interactive completion, where returning no candidates promptly is
    /// better than delaying the shell while retries back off.
    pub async fn search_packages(
        &self,
        query: &str,
        limit: usize,
        timeout: std::time::Duration,
    ) -> Result<Vec<PackageSearchResult>, Error> {
        let routing_name = if query.starts_with('@') && !query.contains('/') {
            Cow::Owned(format!("{query}/"))
        } else {
            Cow::Borrowed(query)
        };
        let registry_url = self.config.registry_for(&routing_name);
        let mut url = reqwest::Url::parse(&format!(
            "{}/-/v1/search",
            registry_url.trim_end_matches('/')
        ))
        .map_err(|error| Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, error)))?;
        url.query_pairs_mut()
            .append_pair("text", query)
            .append_pair("size", &limit.clamp(1, 250).to_string());
        let response = self
            .authed_for_package(
                self.http_for_package(registry_url, &routing_name).get(url),
                registry_url,
                &routing_name,
            )
            .timeout(timeout)
            .header("Accept", "application/json")
            .send()
            .await?
            .error_for_status()?;
        let bytes = read_body_capped(response, 2 << 20, "package search").await?;
        let body: PackageSearchResponse = serde_json::from_slice(&bytes)
            .map_err(|error| Error::Io(std::io::Error::other(error)))?;
        Ok(body
            .objects
            .into_iter()
            .map(|entry| PackageSearchResult {
                name: entry.package.name,
                version: entry.package.version,
                description: entry.package.description,
            })
            .collect())
    }

    pub async fn fetch_advisories_bulk(
        &self,
        pkg_versions: &std::collections::BTreeMap<String, Vec<String>>,
    ) -> Result<serde_json::Value, Error> {
        // The bulk endpoint lives on the default registry; scoped registries
        // don't all implement it, so we always post to the top-level one.
        let registry_url = &self.config.registry;
        let url = format!(
            "{}/-/npm/v1/security/advisories/bulk",
            registry_url.trim_end_matches('/')
        );

        let body = serde_json::to_vec(pkg_versions)
            .map_err(|e| Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, e)))?;

        let resp = self
            .authed(self.http_for(registry_url).post(&url), registry_url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .body(body)
            .send()
            .await?;

        // Some registries (Verdaccio, private mirrors) don't implement the
        // bulk advisory endpoint and return 404. Treat that as "no advisories"
        // — the alternative is making every air-gapped setup pass
        // `--ignore-registry-errors`, which is noisy.
        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(serde_json::Value::Object(serde_json::Map::new()));
        }

        let resp = resp.error_for_status()?;
        check_body_cap(&resp, AUDIT_BODY_CAP, "bulk advisories")?;
        let json: serde_json::Value = resp.json().await?;
        Ok(json)
    }

    /// Fetch a single VersionMetadata via the per-version registry
    /// endpoint `{registry}/{name}/{version}`. Returns ~1-4 KiB JSON
    /// vs the full packument's 100 KiB-2 MiB. Use when caller knows
    /// the exact version, e.g. lockfile drift refetch with locked
    /// version pinned. Wins 200-1000 ms on lockfile CI installs that
    /// trigger re-resolve.
    pub async fn fetch_single_version_metadata(
        &self,
        name: &str,
        version: &str,
    ) -> Result<crate::VersionMetadata, Error> {
        let (packument_url, registry_url) = self.packument_url(name);
        let url = format!("{packument_url}/{version}");
        let resp = self
            .send_metadata_with_retry(&format!("version {name}@{version}"), || {
                self.authed_get_for_package(&url, registry_url, name)
                    .header("Accept", "application/json")
            })
            .await?;
        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::NotFound(format!("{name}@{version}")));
        }
        let resp = resp.error_for_status()?;
        check_body_cap(
            &resp,
            self.fetch_policy.packument_max_bytes,
            "version-metadata",
        )?;
        parse_full_response(resp).await
    }

    /// Fetch the *full* (non-corgi) packument as raw JSON, bypassing the
    /// on-disk cache entirely. Used by mutating commands like `deprecate`
    /// that need a fresh read-modify-write against the authoritative copy
    /// on the registry — a stale cached document would roll back other
    /// publishers' changes on the subsequent PUT.
    pub async fn fetch_packument_json_fresh(&self, name: &str) -> Result<serde_json::Value, Error> {
        let (url, registry_url) = self.packument_url(name);
        let resp = self
            .send_metadata_with_retry(&format!("packument {name}"), || {
                self.authed_get_for_package(&url, registry_url, name)
                    .header("Accept", PACKUMENT_FULL_ACCEPT)
            })
            .await?;
        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::NotFound(name.to_string()));
        }
        let resp = resp.error_for_status()?;
        check_body_cap(&resp, self.fetch_policy.packument_max_bytes, "packument")?;
        let value: serde_json::Value = resp.json().await?;
        Ok(value)
    }

    /// PUT a full packument back to the registry. Used by `deprecate` /
    /// `undeprecate`. Honors `--otp` via the `npm-otp` header.
    ///
    /// Returns the registry's raw response body as `serde_json::Value`
    /// (npm responds with `{ok: true, id, rev}` on success). On HTTP
    /// failure the body is included in the error so 401/403/409 messages
    /// make it to the user.
    pub async fn put_packument(
        &self,
        name: &str,
        body: &serde_json::Value,
        otp: Option<&str>,
    ) -> Result<serde_json::Value, Error> {
        let (url, registry_url) = self.packument_url(name);

        let mut req = self.authed_for_package(
            self.http_for_package(registry_url, name)
                .put(&url)
                .header("Content-Type", "application/json")
                .json(body),
            registry_url,
            name,
        );
        if let Some(code) = otp {
            req = req.header("npm-otp", code);
        }

        let resp = req.send().await?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::RegistryWrite {
                status: status.as_u16(),
                body,
            });
        }
        let value: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
        Ok(value)
    }

    /// Drop any on-disk *full* packument cache entry for `name`, if one
    /// exists. Call this after a successful mutating PUT (deprecate,
    /// dist-tag, ...) so subsequent `aube view` calls don't serve the
    /// pre-mutation document for the remaining TTL window. Missing files
    /// and I/O errors are swallowed — the cache is advisory, not load
    /// bearing.
    pub fn invalidate_full_packument_cache(&self, name: &str, cache_dir: &Path) {
        let registry_url = self.config.registry_for(name).to_string();
        if let Some(path) = packument_full_cache_path(cache_dir, name, &registry_url) {
            let _ = std::fs::remove_file(&path);
        }
    }

    /// Fetch the authoritative dist-tag map for a package from the
    /// registry's `/-/package/<pkg>/dist-tags` endpoint. This is the
    /// same endpoint `npm dist-tag ls` calls. A GET against this
    /// endpoint doesn't require auth for public packages, but we still
    /// attach the user's token so private packages Just Work.
    pub async fn fetch_dist_tags(
        &self,
        name: &str,
    ) -> Result<std::collections::BTreeMap<String, String>, Error> {
        let registry_url = self.registry_url_for(name);
        let url = dist_tag_root_url(registry_url, name);
        let resp = self
            .send_metadata_with_retry(&format!("dist-tags {name}"), || {
                self.authed_get_for_package(&url, registry_url, name)
            })
            .await?;
        check_dist_tag_status(&resp, name)?;
        let map: std::collections::BTreeMap<String, String> =
            resp.error_for_status()?.json().await?;
        Ok(map)
    }

    /// Create or update a dist-tag for a package. The npm registry
    /// expects a PUT with a JSON-string body — e.g. `"1.2.3"`, *with*
    /// the quotes — and Content-Type: application/json. Requires auth.
    pub async fn put_dist_tag(
        &self,
        name: &str,
        tag: &str,
        version: &str,
        otp: Option<&str>,
    ) -> Result<(), Error> {
        let registry_url = self.registry_url_for(name);
        let url = dist_tag_url(registry_url, name, tag);

        // serde_json is already a workspace dep and used elsewhere in
        // this file; hand-serializing would miss control-character
        // escapes and other edge cases. The output is always a JSON
        // string literal like `"1.2.3"`.
        let body = serde_json::to_string(version).map_err(std::io::Error::other)?;

        let mut req = self
            .http_for_package(registry_url, name)
            .put(&url)
            .header("Content-Type", "application/json")
            .body(body);
        if self.config.is_public_npmjs(name) {
            req = req.header("npm-auth-type", "web");
        }
        let req = if let Some(code) = otp {
            req.header("npm-otp", code)
        } else {
            req
        };
        let resp = self
            .authed_for_package(req, registry_url, name)
            .send()
            .await?;
        check_dist_tag_status(&resp, name)?;
        resp.error_for_status()?;
        Ok(())
    }

    /// Remove a dist-tag from a package. Registry DELETE against
    /// `/-/package/<pkg>/dist-tags/<tag>`. Requires auth.
    pub async fn delete_dist_tag(
        &self,
        name: &str,
        tag: &str,
        otp: Option<&str>,
    ) -> Result<(), Error> {
        let registry_url = self.registry_url_for(name);
        let url = dist_tag_url(registry_url, name, tag);
        let mut req = self.http_for_package(registry_url, name).delete(&url);
        if self.config.is_public_npmjs(name) {
            req = req.header("npm-auth-type", "web");
        }
        let req = if let Some(code) = otp {
            req.header("npm-otp", code)
        } else {
            req
        };
        let resp = self
            .authed_for_package(req, registry_url, name)
            .send()
            .await?;
        // 404 here is ambiguous: package doesn't exist vs tag doesn't
        // exist on this package. Surface the `name@tag` form so the
        // caller can render it either way.
        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::NotFound(format!("{name}@{tag}")));
        }
        if matches!(
            resp.status(),
            reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
        ) {
            return Err(Error::Unauthorized);
        }
        resp.error_for_status()?;
        Ok(())
    }

    /// Construct the tarball URL for a package from the registry.
    /// Format: {registry}/{name}/-/{unscoped_name}-{version}.tgz
    pub fn tarball_url(&self, name: &str, version: &str) -> String {
        let registry_url = self.registry_url_for(name);
        let registry = registry_url.trim_end_matches('/');
        let unscoped = if let Some(rest) = name.strip_prefix('@') {
            // @scope/pkg -> pkg
            rest.split('/').nth(1).unwrap_or(rest)
        } else {
            name
        };
        format!("{registry}/{name}/-/{unscoped}-{version}.tgz")
    }
}

#[cfg(test)]
mod search_tests {
    use super::*;
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn package_search_uses_registry_endpoint_and_parses_descriptions() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/-/v1/search"))
            .and(query_param("text", "rea"))
            .and(query_param("size", "5"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "objects": [{
                    "package": {
                        "name": "react",
                        "version": "19.1.0",
                        "description": "React is a JavaScript library"
                    }
                }]
            })))
            .mount(&server)
            .await;

        let client = RegistryClient::new(&server.uri());
        let results = client
            .search_packages("rea", 5, std::time::Duration::from_secs(1))
            .await
            .unwrap();
        assert_eq!(
            results,
            vec![PackageSearchResult {
                name: "react".to_string(),
                version: "19.1.0".to_string(),
                description: Some("React is a JavaScript library".to_string()),
            }]
        );
    }

    #[tokio::test]
    async fn scoped_package_search_uses_its_configured_registry() {
        let default_server = MockServer::start().await;
        let scoped_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/-/v1/search"))
            .and(query_param("text", "@acme/tool"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "objects": [{
                    "package": {"name": "@acme/tool", "version": "2.0.0"}
                }]
            })))
            .expect(1)
            .mount(&scoped_server)
            .await;

        let mut config = crate::config::NpmConfig {
            registry: default_server.uri(),
            ..Default::default()
        };
        config
            .scoped_registries
            .insert("@acme".to_string(), scoped_server.uri());
        let client = RegistryClient::from_config(config);
        let results = client
            .search_packages("@acme/tool", 5, std::time::Duration::from_secs(1))
            .await
            .unwrap();
        assert_eq!(results[0].name, "@acme/tool");
    }

    #[tokio::test]
    async fn incomplete_scope_search_uses_its_configured_registry() {
        let default_server = MockServer::start().await;
        let scoped_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/-/v1/search"))
            .and(query_param("text", "@acme"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "objects": [{
                    "package": {"name": "@acme/tool", "version": "2.0.0"}
                }]
            })))
            .expect(1)
            .mount(&scoped_server)
            .await;

        let mut config = crate::config::NpmConfig {
            registry: default_server.uri(),
            ..Default::default()
        };
        config
            .scoped_registries
            .insert("@acme".to_string(), scoped_server.uri());
        let client = RegistryClient::from_config(config);
        let results = client
            .search_packages("@acme", 5, std::time::Duration::from_secs(1))
            .await
            .unwrap();
        assert_eq!(results[0].name, "@acme/tool");
    }
}