livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The application-specific paths under which every Livewire endpoint is served.
//!
//! Each installation derives one prefix from its application key, so no endpoint sits at a path a
//! scanner can target in every Livewire application.

use std::fmt::Write as _;

use sha2::{Digest, Sha256};

/// The salt mixed with the application key before hashing the endpoint prefix.
const ENDPOINT_SALT: &str = "livewire-endpoint";

/// The number of hexadecimal characters of the key's hash the prefix carries.
const PREFIX_LENGTH: usize = 8;

/// The paths every Livewire endpoint is served under.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoints {
    /// The common prefix, such as `/livewire-1a2b3c4d`.
    prefix: String,
}

impl Endpoints {
    /// `/<livewire-{first 8 hex of sha256(app_key + "livewire-endpoint")}>`.
    #[must_use]
    pub fn new(app_key: &str) -> Self {
        let digest = Sha256::digest(format!("{app_key}{ENDPOINT_SALT}").as_bytes());

        let mut hash = String::with_capacity(PREFIX_LENGTH);
        for byte in &digest[..PREFIX_LENGTH / 2] {
            // Writing to a `String` cannot fail.
            let _ = write!(hash, "{byte:02x}");
        }

        Self {
            prefix: format!("/livewire-{hash}"),
        }
    }

    /// The prefix every endpoint path starts with.
    #[must_use]
    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    /// The path that receives component updates.
    #[must_use]
    pub fn update(&self) -> String {
        format!("{}/update", self.prefix)
    }

    /// The path that serves the browser runtime, in the normal or CSP build, minified or not.
    #[must_use]
    pub fn script(&self, minified: bool, csp: bool) -> String {
        format!("{}/{}", self.prefix, script_file(minified, csp))
    }

    /// The path that serves a minified bundle's source map.
    #[must_use]
    pub fn map(&self, csp: bool) -> String {
        format!("{}/{}", self.prefix, map_file(csp))
    }

    /// The path that receives a temporary file upload.
    #[must_use]
    pub fn upload(&self) -> String {
        format!("{}/upload-file", self.prefix)
    }

    /// The route pattern that previews a temporary file.
    #[must_use]
    pub fn preview(&self) -> String {
        format!("{}/preview-file/{{filename}}", self.prefix)
    }

    /// The route pattern that serves a component's JavaScript module.
    #[must_use]
    pub fn module_js_route(&self) -> String {
        format!("{}/js/{{file}}", self.prefix)
    }

    /// The route pattern that serves a component's CSS module, scoped or global.
    #[must_use]
    pub fn module_css_route(&self) -> String {
        format!("{}/css/{{file}}", self.prefix)
    }

    /// The URL of a component's JavaScript module.
    ///
    /// The name is encoded because `:` and `.` are legal in a component name and not in a path
    /// segment, as upstream's `moduleUrl` does.
    #[must_use]
    pub fn module_js(&self, component: &str) -> String {
        format!("{}/js/{}.js", self.prefix, encode_component_name(component))
    }

    /// The URL of a component's scoped CSS module.
    #[must_use]
    pub fn module_css(&self, component: &str) -> String {
        format!("{}/css/{}.css", self.prefix, encode_component_name(component))
    }

    /// The URL of a component's global CSS module.
    #[must_use]
    pub fn module_global_css(&self, component: &str) -> String {
        format!("{}/css/{}.global.css", self.prefix, encode_component_name(component))
    }
}

/// Encodes a component name for a URL path, as upstream's `moduleUrl` does: `.` becomes `--`,
/// `::` becomes `---`, and `:` becomes `----`.
#[must_use]
pub fn encode_component_name(name: &str) -> String {
    name.replace('.', "--").replace("::", "---").replace(':', "----")
}

/// Reads a component name back out of a URL path segment, in the order that cannot confuse the
/// three encodings: four dashes first, then three, then two.
#[must_use]
pub fn decode_component_name(encoded: &str) -> String {
    encoded.replace("----", ":").replace("---", "::").replace("--", ".")
}

/// The bundle file name a script endpoint serves.
fn script_file(minified: bool, csp: bool) -> String {
    let mut file = String::from("livewire");
    if csp {
        file.push_str(".csp");
    }
    if minified {
        file.push_str(".min");
    }
    file.push_str(".js");
    file
}

/// The source map file name a map endpoint serves.
fn map_file(csp: bool) -> String {
    if csp {
        "livewire.csp.min.js.map".to_owned()
    } else {
        "livewire.min.js.map".to_owned()
    }
}

#[cfg(test)]
mod tests {
    use sha2::{Digest, Sha256};

    use super::Endpoints;

    #[test]
    fn the_prefix_is_stable_for_one_key() {
        assert_eq!(
            Endpoints::new("base64:test-key").prefix(),
            Endpoints::new("base64:test-key").prefix()
        );
    }

    #[test]
    fn the_prefix_differs_for_another_key() {
        assert_ne!(
            Endpoints::new("base64:first").prefix(),
            Endpoints::new("base64:second").prefix()
        );
    }

    #[test]
    fn the_prefix_is_the_hashed_key() {
        let digest = Sha256::digest(b"base64:test-keylivewire-endpoint");
        let expected: String = digest[..4].iter().fold(String::new(), |mut text, byte| {
            use std::fmt::Write as _;
            let _ = write!(text, "{byte:02x}");
            text
        });

        assert_eq!(
            Endpoints::new("base64:test-key").prefix(),
            format!("/livewire-{expected}")
        );
        assert_eq!(Endpoints::new("base64:test-key").prefix().len(), "/livewire-".len() + 8);
    }

    #[test]
    fn every_endpoint_lives_under_the_prefix() {
        let endpoints = Endpoints::new("base64:test-key");
        let prefix = endpoints.prefix();

        for path in [
            endpoints.update(),
            endpoints.script(false, false),
            endpoints.script(true, false),
            endpoints.script(false, true),
            endpoints.script(true, true),
            endpoints.map(false),
            endpoints.map(true),
            endpoints.upload(),
            endpoints.preview(),
            endpoints.module_js_route(),
            endpoints.module_css_route(),
            endpoints.module_js("pages::counter"),
            endpoints.module_css("pages::counter"),
            endpoints.module_global_css("pages::counter"),
        ] {
            assert!(path.starts_with(prefix), "{path} does not start with {prefix}");
        }
    }

    #[test]
    fn every_endpoint_path_is_spelled_as_upstream_does() {
        let endpoints = Endpoints::new("base64:test-key");
        let prefix = endpoints.prefix();

        assert_eq!(endpoints.update(), format!("{prefix}/update"));
        assert_eq!(endpoints.script(false, false), format!("{prefix}/livewire.js"));
        assert_eq!(endpoints.script(true, false), format!("{prefix}/livewire.min.js"));
        assert_eq!(endpoints.script(false, true), format!("{prefix}/livewire.csp.js"));
        assert_eq!(endpoints.script(true, true), format!("{prefix}/livewire.csp.min.js"));
        assert_eq!(endpoints.map(false), format!("{prefix}/livewire.min.js.map"));
        assert_eq!(endpoints.map(true), format!("{prefix}/livewire.csp.min.js.map"));
        assert_eq!(endpoints.upload(), format!("{prefix}/upload-file"));
        assert_eq!(endpoints.preview(), format!("{prefix}/preview-file/{{filename}}"));
        assert_eq!(endpoints.module_js_route(), format!("{prefix}/js/{{file}}"));
        assert_eq!(endpoints.module_css_route(), format!("{prefix}/css/{{file}}"));
        assert_eq!(endpoints.module_js("counter"), format!("{prefix}/js/counter.js"));
        assert_eq!(endpoints.module_css("counter"), format!("{prefix}/css/counter.css"));
        assert_eq!(
            endpoints.module_global_css("counter"),
            format!("{prefix}/css/counter.global.css")
        );
    }
}