tauri_plugin_dev_invoke/lib.rs
1//! Invoke Tauri commands from an ordinary browser during development.
2//!
3//! `tauri-plugin-dev-invoke` starts a small HTTP server next to your app and routes every
4//! request through Tauri's real IPC, so commands run exactly as they do in the webview:
5//! all extractors work ([`tauri::State`], [`tauri::AppHandle`], [`tauri::Window`], ...),
6//! capabilities and permissions are enforced, and plugin commands behave normally.
7//!
8//! It also bridges the *other* direction. Rust pushes values to the frontend by evaluating
9//! `runCallback` inside a webview, which a browser tab can never receive. The plugin injects
10//! a small script into the host webview that relays those callbacks back to the dev server,
11//! which streams them to the browser. That makes [`tauri::ipc::Channel`], the event system
12//! and plugin listeners work in the browser too.
13//!
14//! # Example
15//!
16//! ```rust,ignore
17//! tauri::Builder::default()
18//! .plugin(tauri_plugin_dev_invoke::init())
19//! .run(tauri::generate_context!())
20//! .expect("error while running tauri application");
21//! ```
22//!
23//! Use [`Builder`] to change the port, restrict which browser origins may connect, or pick
24//! the window that browser requests impersonate:
25//!
26//! ```rust,ignore
27//! tauri::Builder::default()
28//! .plugin(
29//! tauri_plugin_dev_invoke::Builder::new()
30//! .port(4000)
31//! .window("main")
32//! .allow_origin("http://localhost:5173")
33//! .build(),
34//! )
35//! .run(tauri::generate_context!())
36//! .expect("error while running tauri application");
37//! ```
38//!
39//! Every one of those can also be set at launch, which is how you run several dev instances
40//! of the same binary side by side:
41//!
42//! ```bash
43//! DEV_INVOKE_PORT=3031 npm run tauri dev
44//! ```
45//!
46//! | Variable | Overrides |
47//! | --- | --- |
48//! | `DEV_INVOKE_HOST` | [`Builder::host`] — an IP address, or `localhost` |
49//! | `DEV_INVOKE_PORT` | [`Builder::port`] |
50//! | `DEV_INVOKE_ALLOWED_ORIGINS` | [`Builder::allowed_origins`] — comma-separated, or `*` for any |
51//! | `DEV_INVOKE_HEADLESS` | [`Builder::headless`] — `1`/`true`/`yes`/`on`, or the negatives |
52//!
53//! The environment wins over the builder, so a hard-coded `.port()` can still be overridden
54//! at launch. A value that does not parse is reported on stderr and ignored.
55//!
56//! # Security
57//!
58//! The server only starts in debug builds. In a release build it is compiled out entirely
59//! unless you enable the `allow-in-release` cargo feature *and* call
60//! [`Builder::enabled_in_release`].
61//!
62//! It binds to `127.0.0.1` and, by default, only answers browser requests coming from your
63//! `build.devUrl` origin. Anything reachable through the server can run any command your
64//! app exposes, so keep it on loopback and keep the origin list tight.
65
66#![cfg_attr(docsrs, feature(doc_cfg))]
67
68#[cfg(any(debug_assertions, feature = "allow-in-release"))]
69mod server;
70
71use std::{
72 net::{IpAddr, Ipv4Addr},
73 time::Duration,
74};
75
76use tauri::{
77 plugin::{Builder as PluginBuilder, TauriPlugin},
78 Runtime,
79};
80
81/// Default TCP port the dev server listens on.
82pub const DEFAULT_PORT: u16 = 3030;
83
84/// Event the host webview uses to hand callbacks back to the plugin when it cannot reach
85/// the dev server over HTTP (for instance because of a restrictive CSP).
86#[cfg(any(debug_assertions, feature = "allow-in-release"))]
87pub(crate) const BRIDGE_EVENT: &str = "dev-invoke://callback";
88
89/// Which browser origins are allowed to talk to the dev server.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum OriginPolicy {
92 /// Allow the `build.devUrl` origin, plus any origin added with
93 /// [`Builder::allow_origin`]. Falls back to [`OriginPolicy::Any`] (with a warning) when
94 /// the app does not configure a `devUrl`.
95 Auto,
96 /// Allow every origin. Convenient, but any web page you visit while the app is running
97 /// can then drive your app's commands.
98 Any,
99 /// Allow exactly these origins.
100 List(Vec<String>),
101}
102
103/// Runtime configuration of the dev server. Build one with [`Builder`].
104#[derive(Debug, Clone)]
105pub struct Config {
106 /// Address the server binds to. Defaults to `127.0.0.1`.
107 pub host: IpAddr,
108 /// Port the server binds to. Defaults to [`DEFAULT_PORT`].
109 pub port: u16,
110 /// Label of the webview browser requests are routed through. Defaults to `main`, then
111 /// to whichever webview exists.
112 pub window: Option<String>,
113 /// Browser origins allowed to reach the server.
114 pub origins: OriginPolicy,
115 /// Extra origins to allow on top of [`OriginPolicy::Auto`].
116 pub extra_origins: Vec<String>,
117 /// Serve files for `convertFileSrc()` over HTTP. Defaults to `true`.
118 pub serve_assets: bool,
119 /// How long a single command may run before the request is answered with an error.
120 pub timeout: Duration,
121 /// Run the server in release builds. Requires the `allow-in-release` cargo feature.
122 pub enabled_in_release: bool,
123 /// Hide the app's windows so it runs as a background relay.
124 pub headless: bool,
125}
126
127impl Default for Config {
128 fn default() -> Self {
129 Self {
130 host: IpAddr::V4(Ipv4Addr::LOCALHOST),
131 port: DEFAULT_PORT,
132 window: None,
133 origins: OriginPolicy::Auto,
134 extra_origins: Vec::new(),
135 serve_assets: true,
136 timeout: Duration::from_secs(600),
137 enabled_in_release: false,
138 headless: false,
139 }
140 }
141}
142
143/// Configures the plugin.
144#[derive(Debug, Clone, Default)]
145pub struct Builder {
146 config: Config,
147}
148
149impl Builder {
150 /// Creates a builder with the default configuration.
151 pub fn new() -> Self {
152 Self::default()
153 }
154
155 /// Sets the address the server binds to.
156 ///
157 /// Only change this if you need to reach the app from another device; the server has no
158 /// authentication, so anything that can connect can run your commands.
159 ///
160 /// Overridden by the `DEV_INVOKE_HOST` environment variable.
161 pub fn host(mut self, host: impl Into<IpAddr>) -> Self {
162 self.config.host = host.into();
163 self
164 }
165
166 /// Sets the port the server binds to. Defaults to [`DEFAULT_PORT`].
167 ///
168 /// Overridden by the `DEV_INVOKE_PORT` environment variable, which is how you give each
169 /// of several dev instances its own listener without rebuilding.
170 pub fn port(mut self, port: u16) -> Self {
171 self.config.port = port;
172 self
173 }
174
175 /// Routes browser requests through the webview with this label.
176 ///
177 /// Browser clients impersonate a single webview: commands taking a [`tauri::Window`] or
178 /// [`tauri::Webview`] receive it, and its capabilities decide what is allowed.
179 pub fn window(mut self, label: impl Into<String>) -> Self {
180 self.config.window = Some(label.into());
181 self
182 }
183
184 /// Allows an additional browser origin, e.g. `http://localhost:5173`.
185 pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
186 self.config.extra_origins.push(origin.into());
187 self
188 }
189
190 /// Replaces the origin allowlist with exactly these origins.
191 ///
192 /// Overridden by the `DEV_INVOKE_ALLOWED_ORIGINS` environment variable, a comma-separated
193 /// list (or `*` for any origin). Origins added with [`Builder::allow_origin`] still apply
194 /// on top of whichever list wins.
195 pub fn allowed_origins<I, S>(mut self, origins: I) -> Self
196 where
197 I: IntoIterator<Item = S>,
198 S: Into<String>,
199 {
200 self.config.origins = OriginPolicy::List(origins.into_iter().map(Into::into).collect());
201 self
202 }
203
204 /// Accepts requests from any origin.
205 ///
206 /// Every page you visit while the app runs can then invoke your app's commands. Prefer
207 /// [`Builder::allow_origin`].
208 pub fn allow_any_origin(mut self) -> Self {
209 self.config.origins = OriginPolicy::Any;
210 self
211 }
212
213 /// Serves files for `convertFileSrc()` over HTTP. Enabled by default.
214 ///
215 /// The endpoint reads arbitrary paths off disk, which is what the `asset:` protocol does
216 /// inside the webview. Disable it if you would rather not expose that on loopback.
217 pub fn serve_assets(mut self, enabled: bool) -> Self {
218 self.config.serve_assets = enabled;
219 self
220 }
221
222 /// Sets how long a single command may run before the request fails. Defaults to 10
223 /// minutes.
224 pub fn timeout(mut self, timeout: Duration) -> Self {
225 self.config.timeout = timeout;
226 self
227 }
228
229 /// Hides the app's windows, so the app runs as a background relay for the browser.
230 ///
231 /// The window is not closed and cannot be: it still loads your frontend, and it is what
232 /// relays events and channel messages to the browser. Headless only means you do not have
233 /// to look at it. On macOS the app also drops out of the Dock and stops taking focus.
234 ///
235 /// Windows are hidden as they are created, which can leave a brief flash on screen. Set
236 /// `"visible": false` on the window in `tauri.conf.json` to avoid it entirely.
237 ///
238 /// Overridden by the `DEV_INVOKE_HEADLESS` environment variable.
239 pub fn headless(mut self, headless: bool) -> Self {
240 self.config.headless = headless;
241 self
242 }
243
244 /// Runs the server in release builds too.
245 ///
246 /// This has no effect unless the `allow-in-release` cargo feature is enabled; without it
247 /// the server is not compiled into release builds at all.
248 pub fn enabled_in_release(mut self, enabled: bool) -> Self {
249 self.config.enabled_in_release = enabled;
250 self
251 }
252
253 /// Builds the plugin.
254 pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
255 #[cfg(any(debug_assertions, feature = "allow-in-release"))]
256 {
257 if cfg!(debug_assertions) || self.config.enabled_in_release {
258 return server::plugin(self.config);
259 }
260 }
261
262 let _ = self;
263 PluginBuilder::new("dev-invoke").build()
264 }
265}
266
267/// Initializes the plugin with the default configuration.
268pub fn init<R: Runtime>() -> TauriPlugin<R> {
269 Builder::new().build()
270}