tauri_plugin_http/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//! Access the HTTP client written in Rust.
6//!
7//! ## Cargo features
8//!
9//! ### Reqwest feature forwards
10//!
11//! These features forwards [`reqwest`](https://docs.rs/reqwest/0.12.28/reqwest/index.html) features:
12//!
13//! - **http2** *(enabled by default)*: Enables HTTP/2 support.
14//! - **native-tls**: Enables TLS functionality provided by native-tls.
15//! - **native-tls-vendored**: Enables the vendored feature of native-tls.
16//! - **native-tls-alpn**: Enables the alpn feature of native-tls.
17//! - **rustls-tls** *(enabled by default)*: Enables TLS functionality provided by rustls. Equivalent to
18//! rustls-tls-webpki-roots.
19//! - **rustls-tls-manual-roots**: Enables TLS functionality provided by rustls, without setting any root
20//! certificates. Roots have to be specified manually.
21//! - **rustls-tls-webpki-roots**: Enables TLS functionality provided by rustls, while using root certificates
22//! from the webpki-roots crate.
23//! - **rustls-tls-native-roots**: Enables TLS functionality provided by rustls, while using root certificates
24//! from the rustls-native-certs crate.
25//! - **blocking**: Provides the [blocking](https://docs.rs/reqwest/0.12.28/reqwest/blocking/index.html) client API.
26//! - **charset** *(enabled by default)*: Improved support for decoding text.
27//! - **cookies** *(enabled by default)*: Provides cookie session support.
28//! - **gzip**: Provides response body gzip decompression.
29//! - **brotli**: Provides response body brotli decompression.
30//! - **zstd**: Provides response body zstd decompression.
31//! - **deflate**: Provides response body deflate decompression.
32//! - **json**: Provides serialization and deserialization for JSON bodies.
33//! - **multipart**: Provides functionality for multipart forms.
34//! - **stream**: Adds support for futures::Stream.
35//! - **socks**: Provides SOCKS5 proxy support.
36//! - **trust-dns**: Enables a trust-dns/Hickory DNS async resolver instead of the default threadpool using
37//! getaddrinfo.
38//! - **system-proxy** *(enabled by default)*: Use Windows and macOS system proxy settings automatically.
39//!
40//! ### tauri-plugin-http features
41//!
42//! - **tracing**: Adds request, response, and cookie-store diagnostics through `tracing`.
43//! - **unsafe-headers**: Allows webview requests to send any headers.
44//! - **dangerous-settings**: Allows dangerous client settings such as accepting invalid certificates or hostnames.
45//!
46//! ## Security
47//!
48//! The URL scope is checked on every hop of a redirect chain, not only on the URL requested by
49//! the frontend, so every redirect target must also be allowed by the scope. Otherwise a server on
50//! an allowed origin could redirect the request to any other origin - a `localhost` service, an
51//! internal host or a cloud metadata endpoint - and hand its response to the webview.
52
53pub use reqwest;
54use tauri::{
55 Manager, Runtime,
56 plugin::{Builder, TauriPlugin},
57};
58
59pub use error::{Error, Result};
60
61mod commands;
62mod error;
63#[cfg(feature = "cookies")]
64mod reqwest_cookie_store;
65mod scope;
66
67#[cfg(feature = "cookies")]
68const COOKIES_FILENAME: &str = ".cookies";
69
70pub(crate) struct Http {
71 #[cfg(feature = "cookies")]
72 cookies_jar: std::sync::Arc<crate::reqwest_cookie_store::CookieStoreMutex>,
73}
74
75pub fn init<R: Runtime>() -> TauriPlugin<R> {
76 Builder::new("http")
77 .setup(|app, _api| {
78 #[cfg(feature = "cookies")]
79 let cookies_jar = {
80 use crate::reqwest_cookie_store::*;
81 use std::fs::File;
82 use std::io::BufReader;
83
84 let cache_dir = app.path().app_cache_dir()?;
85 std::fs::create_dir_all(&cache_dir)?;
86
87 let path = cache_dir.join(COOKIES_FILENAME);
88 let file = File::options()
89 .create(true)
90 .append(true)
91 .read(true)
92 .open(&path)?;
93
94 let reader = BufReader::new(file);
95 CookieStoreMutex::load(path.clone(), reader).unwrap_or_else(|_e| {
96 #[cfg(feature = "tracing")]
97 tracing::warn!(
98 "failed to load cookie store: {_e}, falling back to empty store"
99 );
100 CookieStoreMutex::new(path, Default::default())
101 })
102 };
103
104 let state = Http {
105 #[cfg(feature = "cookies")]
106 cookies_jar: std::sync::Arc::new(cookies_jar),
107 };
108
109 app.manage(state);
110
111 Ok(())
112 })
113 .on_event(|app, event| {
114 #[cfg(feature = "cookies")]
115 if let tauri::RunEvent::Exit = event {
116 let state = app.state::<Http>();
117
118 match state.cookies_jar.request_save() {
119 Ok(rx) => {
120 let _ = rx.recv();
121 }
122 Err(_e) => {
123 #[cfg(feature = "tracing")]
124 tracing::error!("failed to save cookie jar: {_e}");
125 }
126 }
127 }
128
129 #[cfg(not(feature = "cookies"))]
130 let _ = (app, event);
131 })
132 .invoke_handler(tauri::generate_handler![
133 commands::fetch,
134 commands::fetch_cancel,
135 commands::fetch_send,
136 commands::fetch_read_body,
137 commands::fetch_cancel_body,
138 ])
139 .build()
140}