Skip to main content

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//!
52//! The environment wins over the builder, so a hard-coded `.port()` can still be overridden
53//! at launch. A value that does not parse is reported on stderr and ignored.
54//!
55//! # Security
56//!
57//! The server only starts in debug builds. In a release build it is compiled out entirely
58//! unless you enable the `allow-in-release` cargo feature *and* call
59//! [`Builder::enabled_in_release`].
60//!
61//! It binds to `127.0.0.1` and, by default, only answers browser requests coming from your
62//! `build.devUrl` origin. Anything reachable through the server can run any command your
63//! app exposes, so keep it on loopback and keep the origin list tight.
64
65#![cfg_attr(docsrs, feature(doc_cfg))]
66
67#[cfg(any(debug_assertions, feature = "allow-in-release"))]
68mod server;
69
70use std::{
71    net::{IpAddr, Ipv4Addr},
72    time::Duration,
73};
74
75use tauri::{
76    plugin::{Builder as PluginBuilder, TauriPlugin},
77    Runtime,
78};
79
80/// Default TCP port the dev server listens on.
81pub const DEFAULT_PORT: u16 = 3030;
82
83/// Event the host webview uses to hand callbacks back to the plugin when it cannot reach
84/// the dev server over HTTP (for instance because of a restrictive CSP).
85#[cfg(any(debug_assertions, feature = "allow-in-release"))]
86pub(crate) const BRIDGE_EVENT: &str = "dev-invoke://callback";
87
88/// Which browser origins are allowed to talk to the dev server.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum OriginPolicy {
91    /// Allow the `build.devUrl` origin, plus any origin added with
92    /// [`Builder::allow_origin`]. Falls back to [`OriginPolicy::Any`] (with a warning) when
93    /// the app does not configure a `devUrl`.
94    Auto,
95    /// Allow every origin. Convenient, but any web page you visit while the app is running
96    /// can then drive your app's commands.
97    Any,
98    /// Allow exactly these origins.
99    List(Vec<String>),
100}
101
102/// Runtime configuration of the dev server. Build one with [`Builder`].
103#[derive(Debug, Clone)]
104pub struct Config {
105    /// Address the server binds to. Defaults to `127.0.0.1`.
106    pub host: IpAddr,
107    /// Port the server binds to. Defaults to [`DEFAULT_PORT`].
108    pub port: u16,
109    /// Label of the webview browser requests are routed through. Defaults to `main`, then
110    /// to whichever webview exists.
111    pub window: Option<String>,
112    /// Browser origins allowed to reach the server.
113    pub origins: OriginPolicy,
114    /// Extra origins to allow on top of [`OriginPolicy::Auto`].
115    pub extra_origins: Vec<String>,
116    /// Serve files for `convertFileSrc()` over HTTP. Defaults to `true`.
117    pub serve_assets: bool,
118    /// How long a single command may run before the request is answered with an error.
119    pub timeout: Duration,
120    /// Run the server in release builds. Requires the `allow-in-release` cargo feature.
121    pub enabled_in_release: bool,
122}
123
124impl Default for Config {
125    fn default() -> Self {
126        Self {
127            host: IpAddr::V4(Ipv4Addr::LOCALHOST),
128            port: DEFAULT_PORT,
129            window: None,
130            origins: OriginPolicy::Auto,
131            extra_origins: Vec::new(),
132            serve_assets: true,
133            timeout: Duration::from_secs(600),
134            enabled_in_release: false,
135        }
136    }
137}
138
139/// Configures the plugin.
140#[derive(Debug, Clone, Default)]
141pub struct Builder {
142    config: Config,
143}
144
145impl Builder {
146    /// Creates a builder with the default configuration.
147    pub fn new() -> Self {
148        Self::default()
149    }
150
151    /// Sets the address the server binds to.
152    ///
153    /// Only change this if you need to reach the app from another device; the server has no
154    /// authentication, so anything that can connect can run your commands.
155    ///
156    /// Overridden by the `DEV_INVOKE_HOST` environment variable.
157    pub fn host(mut self, host: impl Into<IpAddr>) -> Self {
158        self.config.host = host.into();
159        self
160    }
161
162    /// Sets the port the server binds to. Defaults to [`DEFAULT_PORT`].
163    ///
164    /// Overridden by the `DEV_INVOKE_PORT` environment variable, which is how you give each
165    /// of several dev instances its own listener without rebuilding.
166    pub fn port(mut self, port: u16) -> Self {
167        self.config.port = port;
168        self
169    }
170
171    /// Routes browser requests through the webview with this label.
172    ///
173    /// Browser clients impersonate a single webview: commands taking a [`tauri::Window`] or
174    /// [`tauri::Webview`] receive it, and its capabilities decide what is allowed.
175    pub fn window(mut self, label: impl Into<String>) -> Self {
176        self.config.window = Some(label.into());
177        self
178    }
179
180    /// Allows an additional browser origin, e.g. `http://localhost:5173`.
181    pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
182        self.config.extra_origins.push(origin.into());
183        self
184    }
185
186    /// Replaces the origin allowlist with exactly these origins.
187    ///
188    /// Overridden by the `DEV_INVOKE_ALLOWED_ORIGINS` environment variable, a comma-separated
189    /// list (or `*` for any origin). Origins added with [`Builder::allow_origin`] still apply
190    /// on top of whichever list wins.
191    pub fn allowed_origins<I, S>(mut self, origins: I) -> Self
192    where
193        I: IntoIterator<Item = S>,
194        S: Into<String>,
195    {
196        self.config.origins = OriginPolicy::List(origins.into_iter().map(Into::into).collect());
197        self
198    }
199
200    /// Accepts requests from any origin.
201    ///
202    /// Every page you visit while the app runs can then invoke your app's commands. Prefer
203    /// [`Builder::allow_origin`].
204    pub fn allow_any_origin(mut self) -> Self {
205        self.config.origins = OriginPolicy::Any;
206        self
207    }
208
209    /// Serves files for `convertFileSrc()` over HTTP. Enabled by default.
210    ///
211    /// The endpoint reads arbitrary paths off disk, which is what the `asset:` protocol does
212    /// inside the webview. Disable it if you would rather not expose that on loopback.
213    pub fn serve_assets(mut self, enabled: bool) -> Self {
214        self.config.serve_assets = enabled;
215        self
216    }
217
218    /// Sets how long a single command may run before the request fails. Defaults to 10
219    /// minutes.
220    pub fn timeout(mut self, timeout: Duration) -> Self {
221        self.config.timeout = timeout;
222        self
223    }
224
225    /// Runs the server in release builds too.
226    ///
227    /// This has no effect unless the `allow-in-release` cargo feature is enabled; without it
228    /// the server is not compiled into release builds at all.
229    pub fn enabled_in_release(mut self, enabled: bool) -> Self {
230        self.config.enabled_in_release = enabled;
231        self
232    }
233
234    /// Builds the plugin.
235    pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
236        #[cfg(any(debug_assertions, feature = "allow-in-release"))]
237        {
238            if cfg!(debug_assertions) || self.config.enabled_in_release {
239                return server::plugin(self.config);
240            }
241        }
242
243        let _ = self;
244        PluginBuilder::new("dev-invoke").build()
245    }
246}
247
248/// Initializes the plugin with the default configuration.
249pub fn init<R: Runtime>() -> TauriPlugin<R> {
250    Builder::new().build()
251}