Skip to main content

tapid_core/
lib.rs

1use std::{fmt, str::FromStr};
2
3use base64::{
4    Engine as _,
5    engine::general_purpose::{STANDARD, STANDARD_NO_PAD},
6};
7
8#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
9pub struct PackageName(String);
10
11impl PackageName {
12    pub fn as_str(&self) -> &str {
13        &self.0
14    }
15}
16
17impl FromStr for PackageName {
18    type Err = DomainError;
19
20    fn from_str(value: &str) -> Result<Self, Self::Err> {
21        if value.is_empty()
22            || value.len() > 214
23            || value.starts_with('.')
24            || value.starts_with('_')
25            || value.ends_with('.')
26            || value.ends_with('_')
27            || value.chars().any(char::is_whitespace)
28        {
29            return Err(DomainError::InvalidPackageName(value.to_owned()));
30        }
31
32        if value.starts_with('@') {
33            let mut parts = value.split('/');
34            let scope = parts.next().unwrap_or_default();
35            let name = parts.next().unwrap_or_default();
36            if parts.next().is_some()
37                || scope.len() < 2
38                || name.is_empty()
39                || scope[1..].chars().any(|c| !is_name_character(c))
40                || name.chars().any(|c| !is_name_character(c))
41            {
42                return Err(DomainError::InvalidPackageName(value.to_owned()));
43            }
44        } else if value.chars().any(|c| !is_name_character(c)) {
45            return Err(DomainError::InvalidPackageName(value.to_owned()));
46        }
47
48        Ok(Self(value.to_owned()))
49    }
50}
51
52impl fmt::Display for PackageName {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        self.0.fmt(f)
55    }
56}
57
58/// A canonical SemVer package identity without build metadata.
59///
60/// Prerelease identifiers are preserved because npm packages may depend on an
61/// exact prerelease. Build metadata is rejected because it does not participate
62/// in SemVer precedence and would make registry identities ambiguous.
63#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
64pub struct PackageVersion(semver::Version);
65
66impl PackageVersion {
67    /// Constructs a stable package version with no prerelease identifier.
68    pub fn stable(major: u64, minor: u64, patch: u64) -> Self {
69        Self(semver::Version::new(major, minor, patch))
70    }
71
72    /// Returns the SemVer major component.
73    pub fn major(&self) -> u64 {
74        self.0.major
75    }
76
77    /// Returns the SemVer minor component.
78    pub fn minor(&self) -> u64 {
79        self.0.minor
80    }
81
82    /// Returns the SemVer patch component.
83    pub fn patch(&self) -> u64 {
84        self.0.patch
85    }
86
87    /// Returns the canonical prerelease identifier sequence when present.
88    pub fn prerelease(&self) -> Option<&str> {
89        (!self.0.pre.is_empty()).then(|| self.0.pre.as_str())
90    }
91}
92
93impl FromStr for PackageVersion {
94    type Err = DomainError;
95
96    fn from_str(value: &str) -> Result<Self, Self::Err> {
97        let version = semver::Version::parse(value)
98            .map_err(|_| DomainError::InvalidPackageVersion(value.to_owned()))?;
99        if !version.build.is_empty() {
100            return Err(DomainError::InvalidPackageVersion(value.to_owned()));
101        }
102        Ok(Self(version))
103    }
104}
105
106impl fmt::Display for PackageVersion {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        self.0.fmt(f)
109    }
110}
111
112#[derive(Clone, Debug, Eq, Hash, PartialEq)]
113pub struct ArtifactDigest(String);
114
115impl ArtifactDigest {
116    pub fn as_str(&self) -> &str {
117        &self.0
118    }
119}
120
121impl FromStr for ArtifactDigest {
122    type Err = DomainError;
123
124    fn from_str(value: &str) -> Result<Self, Self::Err> {
125        let Some(hex) = value.strip_prefix("sha256-") else {
126            return Err(DomainError::InvalidArtifactDigest(value.to_owned()));
127        };
128        if hex.len() != 64 || hex.chars().any(|c| !c.is_ascii_hexdigit()) {
129            return Err(DomainError::InvalidArtifactDigest(value.to_owned()));
130        }
131        Ok(Self(value.to_ascii_lowercase()))
132    }
133}
134
135impl fmt::Display for ArtifactDigest {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        self.0.fmt(f)
138    }
139}
140
141#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
142pub struct RegistryOrigin(String);
143
144impl RegistryOrigin {
145    pub fn as_str(&self) -> &str {
146        &self.0
147    }
148}
149
150impl FromStr for RegistryOrigin {
151    type Err = DomainError;
152
153    fn from_str(value: &str) -> Result<Self, Self::Err> {
154        let trimmed = value.trim_end_matches('/');
155        let valid = trimmed.starts_with("https://")
156            && trimmed.len() > "https://".len()
157            && !trimmed.contains(['@', '?', '#', '|'])
158            && trimmed[8..]
159                .split('/')
160                .next()
161                .is_some_and(|host| !host.is_empty());
162        if !valid {
163            return Err(DomainError::InvalidRegistryOrigin(value.to_owned()));
164        }
165        Ok(Self(trimmed.to_owned()))
166    }
167}
168
169impl fmt::Display for RegistryOrigin {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        self.0.fmt(f)
172    }
173}
174
175#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
176pub struct PackageInstanceId {
177    pub registry: RegistryOrigin,
178    pub name: PackageName,
179    pub version: PackageVersion,
180}
181
182impl PackageInstanceId {
183    pub fn new(registry: RegistryOrigin, name: PackageName, version: PackageVersion) -> Self {
184        Self {
185            registry,
186            name,
187            version,
188        }
189    }
190}
191
192#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
193pub struct PackageIntegrity(String);
194
195impl PackageIntegrity {
196    pub fn as_str(&self) -> &str {
197        &self.0
198    }
199}
200
201impl FromStr for PackageIntegrity {
202    type Err = DomainError;
203
204    fn from_str(value: &str) -> Result<Self, Self::Err> {
205        let Some(encoded) = value.strip_prefix("sha512-") else {
206            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
207        };
208        let decoded = if encoded.len() == 86 && !encoded.contains('=') {
209            STANDARD_NO_PAD.decode(encoded)
210        } else if encoded.len() == 88 && encoded.ends_with("==") {
211            STANDARD.decode(encoded)
212        } else {
213            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
214        };
215        let Ok(digest) = decoded else {
216            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
217        };
218        if digest.len() != 64 {
219            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
220        }
221        Ok(Self(format!("sha512-{}", STANDARD.encode(digest))))
222    }
223}
224
225impl fmt::Display for PackageIntegrity {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        self.0.fmt(f)
228    }
229}
230
231#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
232pub struct PeerContext(std::collections::BTreeMap<PackageName, PackageVersion>);
233
234impl PeerContext {
235    pub fn with(mut self, name: PackageName, version: PackageVersion) -> Self {
236        self.0.insert(name, version);
237        self
238    }
239    pub fn entries(&self) -> &std::collections::BTreeMap<PackageName, PackageVersion> {
240        &self.0
241    }
242}
243
244impl fmt::Display for PeerContext {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        let mut first = true;
247        for (name, version) in &self.0 {
248            if !first {
249                f.write_str(",")?;
250            }
251            first = false;
252            write!(f, "{name}@{version}")?;
253        }
254        Ok(())
255    }
256}
257
258#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
259pub struct PlatformContext {
260    pub os: Option<String>,
261    pub cpu: Option<String>,
262    pub libc: Option<String>,
263}
264
265impl PlatformContext {
266    pub fn new(
267        os: Option<&str>,
268        cpu: Option<&str>,
269        libc: Option<&str>,
270    ) -> Result<Self, DomainError> {
271        let context = Self {
272            os: os.map(str::to_owned),
273            cpu: cpu.map(str::to_owned),
274            libc: libc.map(str::to_owned),
275        };
276        if [&context.os, &context.cpu, &context.libc]
277            .into_iter()
278            .flatten()
279            .any(|v| {
280                v.is_empty()
281                    || v.chars().any(char::is_whitespace)
282                    || v.chars().any(char::is_control)
283                    || v == "-"
284                    || v.contains('|')
285            })
286        {
287            return Err(DomainError::InvalidPlatformContext);
288        }
289        Ok(context)
290    }
291}
292
293impl fmt::Display for PlatformContext {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        if self.os.is_none() && self.cpu.is_none() && self.libc.is_none() {
296            return Ok(());
297        }
298        let values = [&self.os, &self.cpu, &self.libc];
299        for (index, value) in values.into_iter().enumerate() {
300            if index > 0 {
301                f.write_str("-")?;
302            }
303            if let Some(value) = value {
304                f.write_str(value)?;
305            }
306        }
307        Ok(())
308    }
309}
310
311#[derive(Clone, Debug, Eq, PartialEq)]
312pub enum DomainError {
313    InvalidPackageName(String),
314    InvalidPackageVersion(String),
315    InvalidArtifactDigest(String),
316    InvalidRegistryOrigin(String),
317    InvalidPackageIntegrity(String),
318    InvalidPlatformContext,
319}
320
321impl fmt::Display for DomainError {
322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323        match self {
324            Self::InvalidPackageName(value) => write!(f, "invalid package name: {value}"),
325            Self::InvalidPackageVersion(value) => write!(f, "invalid package version: {value}"),
326            Self::InvalidArtifactDigest(value) => write!(f, "invalid artifact digest: {value}"),
327            Self::InvalidRegistryOrigin(value) => write!(f, "invalid registry origin: {value}"),
328            Self::InvalidPackageIntegrity(value) => write!(f, "invalid package integrity: {value}"),
329            Self::InvalidPlatformContext => f.write_str("invalid platform context"),
330        }
331    }
332}
333
334impl std::error::Error for DomainError {}
335
336fn is_name_character(character: char) -> bool {
337    character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    #[test]
345    fn accepts_scoped_and_unscoped_package_names() {
346        assert!("tapid".parse::<PackageName>().is_ok());
347        assert!("@tapid/core".parse::<PackageName>().is_ok());
348    }
349
350    #[test]
351    fn rejects_unsafe_package_names() {
352        for value in [
353            "",
354            "../tapid",
355            "@tapid",
356            "@tapid/core/extra",
357            "tap id",
358            "tapid/core",
359        ] {
360            assert!(value.parse::<PackageName>().is_err(), "accepted {value}");
361        }
362    }
363
364    #[test]
365    fn parses_canonical_versions() {
366        let version = "1.2.3".parse::<PackageVersion>().unwrap();
367        assert_eq!(version.to_string(), "1.2.3");
368        assert!("01.2.3".parse::<PackageVersion>().is_err());
369    }
370
371    #[test]
372    fn parses_canonical_prerelease_versions_without_build_metadata() {
373        let version = "5.20260811.1-alpha".parse::<PackageVersion>().unwrap();
374        assert_eq!(version.to_string(), "5.20260811.1-alpha");
375        assert_eq!(version.prerelease(), Some("alpha"));
376        assert!("1.2.3+build.1".parse::<PackageVersion>().is_err());
377        assert!("1.2.3-01".parse::<PackageVersion>().is_err());
378    }
379
380    #[test]
381    fn accepts_only_sha256_digests() {
382        let digest = format!("sha256-{}", "A".repeat(64))
383            .parse::<ArtifactDigest>()
384            .unwrap();
385        assert_eq!(digest.to_string(), format!("sha256-{}", "a".repeat(64)));
386        assert!("sha512-deadbeef".parse::<ArtifactDigest>().is_err());
387    }
388
389    #[test]
390    fn registry_origin_is_typed_and_canonical_without_secrets() {
391        let origin = "https://REGISTRY.example.test/"
392            .parse::<RegistryOrigin>()
393            .unwrap();
394        assert_eq!(origin.as_str(), "https://REGISTRY.example.test");
395        assert!(
396            "http://registry.example.test"
397                .parse::<RegistryOrigin>()
398                .is_err()
399        );
400        assert!(
401            "https://user:pass@registry.example.test"
402                .parse::<RegistryOrigin>()
403                .is_err()
404        );
405        assert!(
406            "https://registry.example.test/path|ambiguous"
407                .parse::<RegistryOrigin>()
408                .is_err()
409        );
410    }
411
412    #[test]
413    fn integrity_round_trips_canonical_padded_sha512() {
414        let value = "sha512-vjezHzaHfTgpmqTTye2FWJ751nFdp6l4EtqfRsd2sylZY73USlHKS75q67jhw5cb7uMi0xRAdd1MiTHAfaR9TA==".to_owned();
415        let integrity = value.parse::<PackageIntegrity>().unwrap();
416        assert_eq!(integrity.to_string(), value);
417    }
418
419    #[test]
420    fn package_integrity_requires_canonical_base64_for_exactly_64_bytes() {
421        let unpadded = format!("sha512-{}", "A".repeat(86));
422        let padded = format!("{unpadded}==");
423        assert_eq!(
424            unpadded.parse::<PackageIntegrity>().unwrap().to_string(),
425            padded
426        );
427        assert!(padded.parse::<PackageIntegrity>().is_ok());
428
429        for invalid in [
430            format!("sha512-{}", "A".repeat(88)),
431            format!("sha512-{}=", "A".repeat(86)),
432            format!("sha512-{}===", "A".repeat(85)),
433        ] {
434            assert!(
435                invalid.parse::<PackageIntegrity>().is_err(),
436                "accepted {invalid}"
437            );
438        }
439    }
440
441    #[test]
442    fn package_instance_identity_includes_registry() {
443        let name: PackageName = "tapid".parse().unwrap();
444        let version: PackageVersion = "1.0.0".parse().unwrap();
445        let first = PackageInstanceId::new(
446            "https://one.example".parse().unwrap(),
447            name.clone(),
448            version.clone(),
449        );
450        let second = PackageInstanceId::new("https://two.example".parse().unwrap(), name, version);
451        assert_ne!(first, second);
452    }
453
454    #[test]
455    fn contexts_have_deterministic_empty_and_nonempty_forms() {
456        let peer = PeerContext::default().with("react".parse().unwrap(), "18.2.0".parse().unwrap());
457        assert_eq!(peer.to_string(), "react@18.2.0");
458        let platform = PlatformContext::new(Some("linux"), Some("x86_64"), Some("gnu")).unwrap();
459        assert_eq!(platform.to_string(), "linux-x86_64-gnu");
460        assert!(PlatformContext::new(Some("linux-x"), None, None).is_ok());
461        assert!(PlatformContext::new(Some("-"), None, None).is_err());
462        assert!(PlatformContext::new(Some("linux|custom"), None, None).is_err());
463        assert!(PlatformContext::new(Some("linux\u{0000}"), None, None).is_err());
464        assert!(PlatformContext::new(Some("linux\u{0007}"), None, None).is_err());
465        assert_eq!(
466            PlatformContext::new(None, Some("x86_64"), None)
467                .unwrap()
468                .to_string(),
469            "-x86_64-"
470        );
471        assert_eq!(
472            PlatformContext::new(Some("linux"), None, Some("gnu"))
473                .unwrap()
474                .to_string(),
475            "linux--gnu"
476        );
477    }
478}