Skip to main content

compmd_host/registry/
proxy.rs

1//! A host's `registry/` proxy in Rust ([resolving registry packs], decision 9; [the Tauri plugin], decision 11), as
2//! `@compmd/registry`'s `registryProxy` is in JavaScript: it passes a pack's abbreviated metadata and its tarballs on
3//! from the host's registries, so a registry never learns who reads which document. It answers nothing else, passes
4//! on no credentials and keeps nothing; the page checks what it passes on, as it checks a registry's own answers.
5//!
6//! [resolving registry packs]: https://github.com/comp-markdown/compmd/blob/main/docs/resolving-registry-packs.md
7//! [the Tauri plugin]: https://github.com/comp-markdown/compmd/blob/main/docs/tauri-plugin.md
8
9use compmd_pack::PackName;
10use http::{Response, StatusCode, header};
11use serde_json::Value;
12
13use super::client::Client;
14use super::metadata::{ABBREVIATED, answered_versions};
15use super::options::Options;
16use super::step::Answer;
17
18/// Where a version's tarball is under the proxy's base.
19const TARBALL: &str = "-/tarball/";
20
21/// The proxy of a host's registries.
22#[derive(Clone, Debug)]
23pub struct Proxy {
24    options: Options,
25    client: Client,
26}
27
28/// An answer of `status` with `text`.
29fn text(status: StatusCode, text: &str) -> Response<Vec<u8>> {
30    Response::builder()
31        .status(status)
32        .header(header::CONTENT_TYPE, "text/plain")
33        .body(text.as_bytes().to_vec())
34        .unwrap_or_default()
35}
36
37/// `path` with its `%XX` escapes decoded; `None` when it doesn't decode to UTF-8.
38fn decoded(path: &str) -> Option<String> {
39    let bytes = path.as_bytes();
40    let mut out = Vec::with_capacity(bytes.len());
41    let mut at = 0;
42    while at < bytes.len() {
43        let escape = (bytes[at] == b'%')
44            .then(|| path.get(at + 1..at + 3))
45            .flatten()
46            .and_then(|hex| u8::from_str_radix(hex, 16).ok());
47        if let Some(byte) = escape {
48            out.push(byte);
49            at += 3;
50        } else {
51            out.push(bytes[at]);
52            at += 1;
53        }
54    }
55    String::from_utf8(out).ok()
56}
57
58/// What a request under the proxy's base asks for.
59enum Asked {
60    Metadata(PackName),
61    Tarball(PackName, String),
62}
63
64/// What `path`, under the proxy's base, asks for: `<name>`, or `-/tarball/<name>/<version>`.
65fn asked(path: &str) -> Option<Asked> {
66    let path = decoded(path)?;
67    let Some(tarball) = path.strip_prefix(TARBALL) else {
68        return path.parse().ok().map(Asked::Metadata);
69    };
70    let (name, version) = tarball.rsplit_once('/')?;
71    Some(Asked::Tarball(name.parse().ok()?, version.to_owned()))
72}
73
74impl Proxy {
75    /// The proxy of `options`' registries, its tarballs no larger than its size cap, fetched with `client`.
76    #[must_use]
77    pub fn new(options: Options, client: Client) -> Self {
78        Self { options, client }
79    }
80
81    /// The answer to a `GET` of `path`, what follows the proxy's base, which is `base` in full (ending in `/`): a
82    /// pack's metadata, its tarballs' URLs rewritten to the proxy's own, or a tarball's bytes. A pack no registry is
83    /// configured for, or one the registry hasn't, is `404`; a registry that fails, `502`.
84    #[must_use]
85    pub fn answer(&self, path: &str, base: &str) -> Response<Vec<u8>> {
86        let not_found = || text(StatusCode::NOT_FOUND, "Not found");
87        let Some(asked) = asked(path) else {
88            return not_found();
89        };
90        let pack = match &asked {
91            Asked::Metadata(pack) | Asked::Tarball(pack, _) => pack,
92        };
93        let Some(registry) = self.options.registry_of(pack) else {
94            return not_found();
95        };
96        let answered = match &asked {
97            Asked::Metadata(pack) => self.metadata(registry, pack, base),
98            Asked::Tarball(pack, version) => self.tarball(registry, pack, version),
99        };
100        answered.unwrap_or_else(|| text(StatusCode::BAD_GATEWAY, "Bad gateway"))
101    }
102
103    /// `pack`'s metadata from `registry`, each tarball's URL the proxy's own; `None` when the registry fails.
104    fn metadata(&self, registry: &str, pack: &PackName, base: &str) -> Option<Response<Vec<u8>>> {
105        let metadata = self.client.metadata(registry, pack).ok()?;
106        if metadata.status == 404 {
107            return Some(text(StatusCode::NOT_FOUND, "Not found"));
108        }
109        if !(200..300).contains(&metadata.status) {
110            return None;
111        }
112        let mut packument: Value = serde_json::from_str(&metadata.body).ok()?;
113        if let Some(versions) = packument["versions"].as_object_mut() {
114            for (version, entry) in versions {
115                if let Some(dist) = entry.get_mut("dist").and_then(Value::as_object_mut) {
116                    let tarball = format!("{base}{TARBALL}{pack}/{version}");
117                    dist.insert("tarball".to_owned(), Value::String(tarball));
118                }
119            }
120        }
121        Response::builder()
122            .header(header::CONTENT_TYPE, ABBREVIATED)
123            .header(
124                header::CACHE_CONTROL,
125                format!("public, max-age={}", metadata.max_age),
126            )
127            .body(packument.to_string().into_bytes())
128            .ok()
129    }
130
131    /// The tarball of `pack` at `version`, from where `registry`'s metadata says it is; `None` when it fails.
132    fn tarball(&self, registry: &str, pack: &PackName, version: &str) -> Option<Response<Vec<u8>>> {
133        let metadata = self.client.metadata(registry, pack).ok()?;
134        let versions = answered_versions(registry, pack, metadata.status, &metadata.body).ok()?;
135        let Some(info) = versions
136            .iter()
137            .find(|info| info.version.to_string() == version)
138        else {
139            return Some(text(StatusCode::NOT_FOUND, "Not found"));
140        };
141        let Answer::Tarball { bytes } =
142            self.client
143                .tarball(registry, info, self.options.max_pack_size)
144        else {
145            return None;
146        };
147        // A version's tarball never changes.
148        Response::builder()
149            .header(header::CONTENT_TYPE, "application/octet-stream")
150            .header(header::CACHE_CONTROL, "public, max-age=31536000, immutable")
151            .body(bytes)
152            .ok()
153    }
154}
155
156#[cfg(test)]
157mod tests;