Skip to main content

tauri_plugin_localhost/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Expose your apps assets through a localhost server instead of the default custom protocol.
6//!
7//! **Note: This plugins brings considerable security risks and you should only use it if you know what your are doing. If in doubt, use the default custom protocol implementation.**
8
9#![doc(
10    html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
11    html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
12)]
13
14use std::collections::HashMap;
15
16use http::Uri;
17use tauri::{
18    Runtime,
19    plugin::{Builder as PluginBuilder, TauriPlugin},
20};
21use tiny_http::{Header, Response as HttpResponse, Server};
22
23/// An incoming HTTP request received by the localhost server, passed to the
24/// [`Builder::on_request`] hook.
25pub struct Request {
26    url: String,
27}
28
29impl Request {
30    /// The request URL (path and, if present, query string), exactly as sent by the client.
31    pub fn url(&self) -> &str {
32        &self.url
33    }
34}
35
36/// The HTTP response the localhost server is about to send back for a matched asset. Passed
37/// mutably to the [`Builder::on_request`] hook so it can add or override headers before the
38/// response is written to the client.
39pub struct Response {
40    headers: HashMap<String, String>,
41}
42
43impl Response {
44    /// Adds a header to the response, replacing any existing header with the same name.
45    pub fn add_header<H: Into<String>, V: Into<String>>(&mut self, header: H, value: V) {
46        self.headers.insert(header.into(), value.into());
47    }
48}
49
50type OnRequest = Option<Box<dyn Fn(&Request, &mut Response) + Send + Sync>>;
51
52/// Builds the localhost plugin.
53///
54/// **Note: This plugin brings considerable security risks and you should only use it if you know
55/// what you are doing. Because the server has no authentication, any local process can connect to
56/// it and read the assets it serves. If in doubt, use the default custom protocol implementation.**
57pub struct Builder {
58    port: u16,
59    host: Option<String>,
60    on_request: OnRequest,
61}
62
63impl Builder {
64    /// Creates a new [`Builder`] that will serve the app's assets on the given `port`, bound to
65    /// `localhost` unless [`Self::host`] is called.
66    ///
67    /// # Examples
68    ///
69    /// ```no_run
70    /// fn setup<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
71    ///     builder.plugin(
72    ///         tauri_plugin_localhost::Builder::new(9527)
73    ///             .host("127.0.0.1")
74    ///             .on_request(|request, response| {
75    ///                 println!("{}", request.url());
76    ///             })
77    ///             .build(),
78    ///     )
79    /// }
80    /// ```
81    pub fn new(port: u16) -> Self {
82        Self {
83            port,
84            host: None,
85            on_request: None,
86        }
87    }
88
89    /// Sets the host the localhost server binds to. Defaults to `localhost`.
90    pub fn host<H: Into<String>>(mut self, host: H) -> Self {
91        self.host = Some(host.into());
92        self
93    }
94
95    /// Sets a hook that is called for every request that resolves to a known frontend asset,
96    /// right before the response is sent. Use it to inspect the [`Request`] and add or override
97    /// headers on the [`Response`], for example to append custom CORS or caching headers.
98    pub fn on_request<F: Fn(&Request, &mut Response) + Send + Sync + 'static>(
99        mut self,
100        f: F,
101    ) -> Self {
102        self.on_request.replace(Box::new(f));
103        self
104    }
105
106    /// Builds the plugin, ready to be registered with [`tauri::Builder::plugin`].
107    ///
108    /// On setup it spawns a background thread that starts a `tiny_http` server bound to
109    /// `host:port`. For every incoming request whose path resolves to a known frontend asset, the
110    /// server responds with that asset's bytes, automatically setting the `Content-Type`, the
111    /// `Content-Security-Policy` (when the asset has one) and a `Cache-Control: no-cache` header,
112    /// then invoking the [`Self::on_request`] hook (if any) before writing the response.
113    ///
114    /// # Panics
115    ///
116    /// Panics on the background thread if the server fails to bind to `host:port`, or if it fails
117    /// to send a response for a request.
118    pub fn build<R: Runtime>(mut self) -> TauriPlugin<R> {
119        let port = self.port;
120        let host = self.host.unwrap_or("localhost".to_string());
121        let on_request = self.on_request.take();
122
123        PluginBuilder::new("localhost")
124            .setup(move |app, _api| {
125                let asset_resolver = app.asset_resolver();
126                std::thread::spawn(move || {
127                    let server =
128                        Server::http(format!("{host}:{port}")).expect("Unable to spawn server");
129                    for req in server.incoming_requests() {
130                        let path = req
131                            .url()
132                            .parse::<Uri>()
133                            .map(|uri| uri.path().into())
134                            .unwrap_or_else(|_| req.url().into());
135
136                        #[allow(unused_mut)]
137                        if let Some(mut asset) = asset_resolver.get(path) {
138                            let request = Request {
139                                url: req.url().into(),
140                            };
141                            let mut response = Response {
142                                headers: Default::default(),
143                            };
144
145                            response.add_header("Content-Type", asset.mime_type);
146                            if let Some(csp) = asset.csp_header {
147                                response
148                                    .headers
149                                    .insert("Content-Security-Policy".into(), csp);
150                            }
151
152                            response
153                                .headers
154                                .insert("Cache-Control".into(), "no-cache".into());
155
156                            if let Some(on_request) = &on_request {
157                                on_request(&request, &mut response);
158                            }
159
160                            let mut resp = HttpResponse::from_data(asset.bytes);
161                            for (header, value) in response.headers {
162                                if let Ok(h) = Header::from_bytes(header.as_bytes(), value) {
163                                    resp.add_header(h);
164                                }
165                            }
166                            req.respond(resp).expect("unable to setup response");
167                        }
168                    }
169                });
170                Ok(())
171            })
172            .build()
173    }
174}