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/// A canonical, credential-free HTTPS origin for newly resolved identities.
142/// Parsing normalizes host spelling, the default port and slash-only root paths.
143/// Persisted graph readers must reject spelling changes instead of silently
144/// rekeying distinct legacy identities.
145#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
146pub struct RegistryOrigin(String);
147
148impl RegistryOrigin {
149    pub fn as_str(&self) -> &str {
150        &self.0
151    }
152}
153
154impl FromStr for RegistryOrigin {
155    type Err = DomainError;
156
157    fn from_str(value: &str) -> Result<Self, Self::Err> {
158        let parsed = url::Url::parse(value)
159            .map_err(|_| DomainError::InvalidRegistryOrigin(value.to_owned()))?;
160        if parsed.scheme() != "https"
161            || !parsed.username().is_empty()
162            || value.contains("@")
163            || parsed.password().is_some()
164            || parsed.query().is_some()
165            || parsed.fragment().is_some()
166            || parsed.host_str().is_none()
167            || !parsed.path().chars().all(|character| character == '/')
168        {
169            return Err(DomainError::InvalidRegistryOrigin(value.to_owned()));
170        }
171        let host = parsed.host_str().unwrap_or_default().to_ascii_lowercase();
172        let host = if host.contains(":") && !host.starts_with('[') {
173            format!("[{host}]")
174        } else {
175            host
176        };
177        let authority = match parsed.port().filter(|port| *port != 443) {
178            Some(port) => format!("{host}:{port}"),
179            None => host,
180        };
181        Ok(Self(format!("https://{authority}")))
182    }
183}
184
185impl fmt::Display for RegistryOrigin {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        self.0.fmt(f)
188    }
189}
190
191#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
192pub struct PackageInstanceId {
193    pub registry: RegistryOrigin,
194    pub name: PackageName,
195    pub version: PackageVersion,
196}
197
198impl PackageInstanceId {
199    pub fn new(registry: RegistryOrigin, name: PackageName, version: PackageVersion) -> Self {
200        Self {
201            registry,
202            name,
203            version,
204        }
205    }
206}
207
208#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
209pub struct PackageIntegrity(String);
210
211impl PackageIntegrity {
212    pub fn as_str(&self) -> &str {
213        &self.0
214    }
215}
216
217impl FromStr for PackageIntegrity {
218    type Err = DomainError;
219
220    fn from_str(value: &str) -> Result<Self, Self::Err> {
221        let Some(encoded) = value.strip_prefix("sha512-") else {
222            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
223        };
224        let decoded = if encoded.len() == 86 && !encoded.contains('=') {
225            STANDARD_NO_PAD.decode(encoded)
226        } else if encoded.len() == 88 && encoded.ends_with("==") {
227            STANDARD.decode(encoded)
228        } else {
229            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
230        };
231        let Ok(digest) = decoded else {
232            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
233        };
234        if digest.len() != 64 {
235            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
236        }
237        Ok(Self(format!("sha512-{}", STANDARD.encode(digest))))
238    }
239}
240
241impl fmt::Display for PackageIntegrity {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        self.0.fmt(f)
244    }
245}
246
247#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
248pub struct PeerContext(std::collections::BTreeMap<PackageName, PackageVersion>);
249
250impl PeerContext {
251    pub fn with(mut self, name: PackageName, version: PackageVersion) -> Self {
252        self.0.insert(name, version);
253        self
254    }
255    pub fn entries(&self) -> &std::collections::BTreeMap<PackageName, PackageVersion> {
256        &self.0
257    }
258}
259
260impl fmt::Display for PeerContext {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        let mut first = true;
263        for (name, version) in &self.0 {
264            if !first {
265                f.write_str(",")?;
266            }
267            first = false;
268            write!(f, "{name}@{version}")?;
269        }
270        Ok(())
271    }
272}
273
274#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
275pub struct PlatformContext {
276    pub os: Option<String>,
277    pub cpu: Option<String>,
278    pub libc: Option<String>,
279}
280
281impl PlatformContext {
282    pub fn new(
283        os: Option<&str>,
284        cpu: Option<&str>,
285        libc: Option<&str>,
286    ) -> Result<Self, DomainError> {
287        let context = Self {
288            os: os.map(str::to_owned),
289            cpu: cpu.map(str::to_owned),
290            libc: libc.map(str::to_owned),
291        };
292        if [&context.os, &context.cpu, &context.libc]
293            .into_iter()
294            .flatten()
295            .any(|v| {
296                v.is_empty()
297                    || v.chars().any(char::is_whitespace)
298                    || v.chars().any(char::is_control)
299                    || v == "-"
300                    || v.contains('|')
301            })
302        {
303            return Err(DomainError::InvalidPlatformContext);
304        }
305        Ok(context)
306    }
307}
308
309impl fmt::Display for PlatformContext {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        if self.os.is_none() && self.cpu.is_none() && self.libc.is_none() {
312            return Ok(());
313        }
314        let values = [&self.os, &self.cpu, &self.libc];
315        for (index, value) in values.into_iter().enumerate() {
316            if index > 0 {
317                f.write_str("-")?;
318            }
319            if let Some(value) = value {
320                f.write_str(value)?;
321            }
322        }
323        Ok(())
324    }
325}
326
327#[derive(Clone, Debug, Eq, PartialEq)]
328pub enum DomainError {
329    InvalidPackageName(String),
330    InvalidPackageVersion(String),
331    InvalidArtifactDigest(String),
332    InvalidRegistryOrigin(String),
333    InvalidPackageIntegrity(String),
334    InvalidPlatformContext,
335}
336
337impl fmt::Display for DomainError {
338    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339        match self {
340            Self::InvalidPackageName(value) => write!(f, "invalid package name: {value}"),
341            Self::InvalidPackageVersion(value) => write!(f, "invalid package version: {value}"),
342            Self::InvalidArtifactDigest(value) => write!(f, "invalid artifact digest: {value}"),
343            Self::InvalidRegistryOrigin(value) => write!(f, "invalid registry origin: {value}"),
344            Self::InvalidPackageIntegrity(value) => write!(f, "invalid package integrity: {value}"),
345            Self::InvalidPlatformContext => f.write_str("invalid platform context"),
346        }
347    }
348}
349
350impl std::error::Error for DomainError {}
351
352fn is_name_character(character: char) -> bool {
353    character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn accepts_scoped_and_unscoped_package_names() {
362        assert!("tapid".parse::<PackageName>().is_ok());
363        assert!("@tapid/core".parse::<PackageName>().is_ok());
364    }
365
366    #[test]
367    fn rejects_unsafe_package_names() {
368        for value in [
369            "",
370            "../tapid",
371            "@tapid",
372            "@tapid/core/extra",
373            "tap id",
374            "tapid/core",
375        ] {
376            assert!(value.parse::<PackageName>().is_err(), "accepted {value}");
377        }
378    }
379
380    #[test]
381    fn parses_canonical_versions() {
382        let version = "1.2.3".parse::<PackageVersion>().unwrap();
383        assert_eq!(version.to_string(), "1.2.3");
384        assert!("01.2.3".parse::<PackageVersion>().is_err());
385    }
386
387    #[test]
388    fn parses_canonical_prerelease_versions_without_build_metadata() {
389        let version = "5.20260811.1-alpha".parse::<PackageVersion>().unwrap();
390        assert_eq!(version.to_string(), "5.20260811.1-alpha");
391        assert_eq!(version.prerelease(), Some("alpha"));
392        assert!("1.2.3+build.1".parse::<PackageVersion>().is_err());
393        assert!("1.2.3-01".parse::<PackageVersion>().is_err());
394    }
395
396    #[test]
397    fn accepts_only_sha256_digests() {
398        let digest = format!("sha256-{}", "A".repeat(64))
399            .parse::<ArtifactDigest>()
400            .unwrap();
401        assert_eq!(digest.to_string(), format!("sha256-{}", "a".repeat(64)));
402        assert!("sha512-deadbeef".parse::<ArtifactDigest>().is_err());
403    }
404
405    #[test]
406    fn registry_origin_is_typed_and_canonical_without_secrets() {
407        let origin = "https://REGISTRY.example.test:443/"
408            .parse::<RegistryOrigin>()
409            .unwrap();
410        assert_eq!(origin.as_str(), "https://registry.example.test");
411        assert_eq!(
412            "https://registry.example.test///"
413                .parse::<RegistryOrigin>()
414                .unwrap()
415                .as_str(),
416            "https://registry.example.test"
417        );
418        assert_eq!(
419            "https://REGISTRY.example.test"
420                .parse::<RegistryOrigin>()
421                .unwrap(),
422            origin
423        );
424        assert_eq!(
425            "https://registry.example.test:8443"
426                .parse::<RegistryOrigin>()
427                .unwrap()
428                .as_str(),
429            "https://registry.example.test:8443"
430        );
431        assert_eq!(
432            "https://[2001:DB8::1]:443/"
433                .parse::<RegistryOrigin>()
434                .unwrap()
435                .as_str(),
436            "https://[2001:db8::1]"
437        );
438        assert_eq!(
439            "https://[2001:db8::1]:8443"
440                .parse::<RegistryOrigin>()
441                .unwrap()
442                .as_str(),
443            "https://[2001:db8::1]:8443"
444        );
445        assert!(
446            "http://registry.example.test"
447                .parse::<RegistryOrigin>()
448                .is_err()
449        );
450        assert!(
451            "https://user:pass@registry.example.test"
452                .parse::<RegistryOrigin>()
453                .is_err()
454        );
455        assert!(
456            "https://@registry.example.test"
457                .parse::<RegistryOrigin>()
458                .is_err()
459        );
460        assert!(
461            "https://registry.example.test?query"
462                .parse::<RegistryOrigin>()
463                .is_err()
464        );
465        assert!(
466            "https://registry.example.test#fragment"
467                .parse::<RegistryOrigin>()
468                .is_err()
469        );
470        assert!(
471            "https://registry.example.test/path|ambiguous"
472                .parse::<RegistryOrigin>()
473                .is_err()
474        );
475    }
476
477    #[test]
478    fn integrity_round_trips_canonical_padded_sha512() {
479        let value = "sha512-vjezHzaHfTgpmqTTye2FWJ751nFdp6l4EtqfRsd2sylZY73USlHKS75q67jhw5cb7uMi0xRAdd1MiTHAfaR9TA==".to_owned();
480        let integrity = value.parse::<PackageIntegrity>().unwrap();
481        assert_eq!(integrity.to_string(), value);
482    }
483
484    #[test]
485    fn package_integrity_requires_canonical_base64_for_exactly_64_bytes() {
486        let unpadded = format!("sha512-{}", "A".repeat(86));
487        let padded = format!("{unpadded}==");
488        assert_eq!(
489            unpadded.parse::<PackageIntegrity>().unwrap().to_string(),
490            padded
491        );
492        assert!(padded.parse::<PackageIntegrity>().is_ok());
493
494        for invalid in [
495            format!("sha512-{}", "A".repeat(88)),
496            format!("sha512-{}=", "A".repeat(86)),
497            format!("sha512-{}===", "A".repeat(85)),
498        ] {
499            assert!(
500                invalid.parse::<PackageIntegrity>().is_err(),
501                "accepted {invalid}"
502            );
503        }
504    }
505
506    #[test]
507    fn package_instance_identity_includes_registry() {
508        let name: PackageName = "tapid".parse().unwrap();
509        let version: PackageVersion = "1.0.0".parse().unwrap();
510        let first = PackageInstanceId::new(
511            "https://one.example".parse().unwrap(),
512            name.clone(),
513            version.clone(),
514        );
515        let second = PackageInstanceId::new("https://two.example".parse().unwrap(), name, version);
516        assert_ne!(first, second);
517    }
518
519    #[test]
520    fn contexts_have_deterministic_empty_and_nonempty_forms() {
521        let peer = PeerContext::default().with("react".parse().unwrap(), "18.2.0".parse().unwrap());
522        assert_eq!(peer.to_string(), "react@18.2.0");
523        let platform = PlatformContext::new(Some("linux"), Some("x86_64"), Some("gnu")).unwrap();
524        assert_eq!(platform.to_string(), "linux-x86_64-gnu");
525        assert!(PlatformContext::new(Some("linux-x"), None, None).is_ok());
526        assert!(PlatformContext::new(Some("-"), None, None).is_err());
527        assert!(PlatformContext::new(Some("linux|custom"), None, None).is_err());
528        assert!(PlatformContext::new(Some("linux\u{0000}"), None, None).is_err());
529        assert!(PlatformContext::new(Some("linux\u{0007}"), None, None).is_err());
530        assert_eq!(
531            PlatformContext::new(None, Some("x86_64"), None)
532                .unwrap()
533                .to_string(),
534            "-x86_64-"
535        );
536        assert_eq!(
537            PlatformContext::new(Some("linux"), None, Some("gnu"))
538                .unwrap()
539                .to_string(),
540            "linux--gnu"
541        );
542    }
543}