Skip to main content

livewire/
frontend.rs

1//! The application-specific paths under which every Livewire endpoint is served.
2//!
3//! Each installation derives one prefix from its application key, so no endpoint sits at a path a
4//! scanner can target in every Livewire application.
5
6use std::fmt::Write as _;
7
8use sha2::{Digest, Sha256};
9
10/// The salt mixed with the application key before hashing the endpoint prefix.
11const ENDPOINT_SALT: &str = "livewire-endpoint";
12
13/// The number of hexadecimal characters of the key's hash the prefix carries.
14const PREFIX_LENGTH: usize = 8;
15
16/// The paths every Livewire endpoint is served under.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Endpoints {
19    /// The common prefix, such as `/livewire-1a2b3c4d`.
20    prefix: String,
21}
22
23impl Endpoints {
24    /// `/<livewire-{first 8 hex of sha256(app_key + "livewire-endpoint")}>`.
25    #[must_use]
26    pub fn new(app_key: &str) -> Self {
27        let digest = Sha256::digest(format!("{app_key}{ENDPOINT_SALT}").as_bytes());
28
29        let mut hash = String::with_capacity(PREFIX_LENGTH);
30        for byte in &digest[..PREFIX_LENGTH / 2] {
31            // Writing to a `String` cannot fail.
32            let _ = write!(hash, "{byte:02x}");
33        }
34
35        Self {
36            prefix: format!("/livewire-{hash}"),
37        }
38    }
39
40    /// The prefix every endpoint path starts with.
41    #[must_use]
42    pub fn prefix(&self) -> &str {
43        &self.prefix
44    }
45
46    /// The path that receives component updates.
47    #[must_use]
48    pub fn update(&self) -> String {
49        format!("{}/update", self.prefix)
50    }
51
52    /// The path that serves the browser runtime, in the normal or CSP build, minified or not.
53    #[must_use]
54    pub fn script(&self, minified: bool, csp: bool) -> String {
55        format!("{}/{}", self.prefix, script_file(minified, csp))
56    }
57
58    /// The path that serves a minified bundle's source map.
59    #[must_use]
60    pub fn map(&self, csp: bool) -> String {
61        format!("{}/{}", self.prefix, map_file(csp))
62    }
63
64    /// The path that receives a temporary file upload.
65    #[must_use]
66    pub fn upload(&self) -> String {
67        format!("{}/upload-file", self.prefix)
68    }
69
70    /// The route pattern that previews a temporary file.
71    #[must_use]
72    pub fn preview(&self) -> String {
73        format!("{}/preview-file/{{filename}}", self.prefix)
74    }
75
76    /// The route pattern that serves a component's JavaScript module.
77    #[must_use]
78    pub fn module_js_route(&self) -> String {
79        format!("{}/js/{{file}}", self.prefix)
80    }
81
82    /// The route pattern that serves a component's CSS module, scoped or global.
83    #[must_use]
84    pub fn module_css_route(&self) -> String {
85        format!("{}/css/{{file}}", self.prefix)
86    }
87
88    /// The URL of a component's JavaScript module.
89    ///
90    /// The name is encoded because `:` and `.` are legal in a component name and not in a path
91    /// segment, as upstream's `moduleUrl` does.
92    #[must_use]
93    pub fn module_js(&self, component: &str) -> String {
94        format!("{}/js/{}.js", self.prefix, encode_component_name(component))
95    }
96
97    /// The URL of a component's scoped CSS module.
98    #[must_use]
99    pub fn module_css(&self, component: &str) -> String {
100        format!("{}/css/{}.css", self.prefix, encode_component_name(component))
101    }
102
103    /// The URL of a component's global CSS module.
104    #[must_use]
105    pub fn module_global_css(&self, component: &str) -> String {
106        format!("{}/css/{}.global.css", self.prefix, encode_component_name(component))
107    }
108}
109
110/// Encodes a component name for a URL path, as upstream's `moduleUrl` does: `.` becomes `--`,
111/// `::` becomes `---`, and `:` becomes `----`.
112#[must_use]
113pub fn encode_component_name(name: &str) -> String {
114    name.replace('.', "--").replace("::", "---").replace(':', "----")
115}
116
117/// Reads a component name back out of a URL path segment, in the order that cannot confuse the
118/// three encodings: four dashes first, then three, then two.
119#[must_use]
120pub fn decode_component_name(encoded: &str) -> String {
121    encoded.replace("----", ":").replace("---", "::").replace("--", ".")
122}
123
124/// The bundle file name a script endpoint serves.
125fn script_file(minified: bool, csp: bool) -> String {
126    let mut file = String::from("livewire");
127    if csp {
128        file.push_str(".csp");
129    }
130    if minified {
131        file.push_str(".min");
132    }
133    file.push_str(".js");
134    file
135}
136
137/// The source map file name a map endpoint serves.
138fn map_file(csp: bool) -> String {
139    if csp {
140        "livewire.csp.min.js.map".to_owned()
141    } else {
142        "livewire.min.js.map".to_owned()
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use sha2::{Digest, Sha256};
149
150    use super::Endpoints;
151
152    #[test]
153    fn the_prefix_is_stable_for_one_key() {
154        assert_eq!(
155            Endpoints::new("base64:test-key").prefix(),
156            Endpoints::new("base64:test-key").prefix()
157        );
158    }
159
160    #[test]
161    fn the_prefix_differs_for_another_key() {
162        assert_ne!(
163            Endpoints::new("base64:first").prefix(),
164            Endpoints::new("base64:second").prefix()
165        );
166    }
167
168    #[test]
169    fn the_prefix_is_the_hashed_key() {
170        let digest = Sha256::digest(b"base64:test-keylivewire-endpoint");
171        let expected: String = digest[..4].iter().fold(String::new(), |mut text, byte| {
172            use std::fmt::Write as _;
173            let _ = write!(text, "{byte:02x}");
174            text
175        });
176
177        assert_eq!(
178            Endpoints::new("base64:test-key").prefix(),
179            format!("/livewire-{expected}")
180        );
181        assert_eq!(Endpoints::new("base64:test-key").prefix().len(), "/livewire-".len() + 8);
182    }
183
184    #[test]
185    fn every_endpoint_lives_under_the_prefix() {
186        let endpoints = Endpoints::new("base64:test-key");
187        let prefix = endpoints.prefix();
188
189        for path in [
190            endpoints.update(),
191            endpoints.script(false, false),
192            endpoints.script(true, false),
193            endpoints.script(false, true),
194            endpoints.script(true, true),
195            endpoints.map(false),
196            endpoints.map(true),
197            endpoints.upload(),
198            endpoints.preview(),
199            endpoints.module_js_route(),
200            endpoints.module_css_route(),
201            endpoints.module_js("pages::counter"),
202            endpoints.module_css("pages::counter"),
203            endpoints.module_global_css("pages::counter"),
204        ] {
205            assert!(path.starts_with(prefix), "{path} does not start with {prefix}");
206        }
207    }
208
209    #[test]
210    fn every_endpoint_path_is_spelled_as_upstream_does() {
211        let endpoints = Endpoints::new("base64:test-key");
212        let prefix = endpoints.prefix();
213
214        assert_eq!(endpoints.update(), format!("{prefix}/update"));
215        assert_eq!(endpoints.script(false, false), format!("{prefix}/livewire.js"));
216        assert_eq!(endpoints.script(true, false), format!("{prefix}/livewire.min.js"));
217        assert_eq!(endpoints.script(false, true), format!("{prefix}/livewire.csp.js"));
218        assert_eq!(endpoints.script(true, true), format!("{prefix}/livewire.csp.min.js"));
219        assert_eq!(endpoints.map(false), format!("{prefix}/livewire.min.js.map"));
220        assert_eq!(endpoints.map(true), format!("{prefix}/livewire.csp.min.js.map"));
221        assert_eq!(endpoints.upload(), format!("{prefix}/upload-file"));
222        assert_eq!(endpoints.preview(), format!("{prefix}/preview-file/{{filename}}"));
223        assert_eq!(endpoints.module_js_route(), format!("{prefix}/js/{{file}}"));
224        assert_eq!(endpoints.module_css_route(), format!("{prefix}/css/{{file}}"));
225        assert_eq!(endpoints.module_js("counter"), format!("{prefix}/js/counter.js"));
226        assert_eq!(endpoints.module_css("counter"), format!("{prefix}/css/counter.css"));
227        assert_eq!(
228            endpoints.module_global_css("counter"),
229            format!("{prefix}/css/counter.global.css")
230        );
231    }
232}