Skip to main content
← rust.krizaka.comkrizaka.com

tauri_plugin_krizaka/
lib.rs

1//! The Tauri side of `krizaka-rust`: one plugin a Krizaka Mac app adds, so its own `lib.rs` only holds what is the
2//! product's (its commands, each resolving its paths through [`Kit::resolve`]).
3//!
4//! ```ignore
5//! tauri::Builder::default()
6//!     .plugin(tauri_plugin_krizaka::dialog::init())
7//!     .plugin(
8//!         tauri_plugin_krizaka::Builder::new("verikora")
9//!             .link_hosts(["www.verikora.com", "dev.verikora.com"])
10//!             .link_prefixes(["/app", "/verify"])
11//!             .build(),
12//!     )
13//!     .invoke_handler(tauri::generate_handler![read_document])
14//!     .run(tauri::generate_context!())
15//! ```
16//!
17//! What it brings, and what the page reaches through `@krizaka/app-desktop` (capability `krizaka:default`):
18//! - folders the person grants with the native picker, listed, revoked, watched; files dropped on the window
19//!   (event [`DROPPED`]); every path through the kit's one gate ([`krizaka_rust::access::Access`]);
20//! - small secrets in the macOS Keychain (the session token), the `KeyValueStorage` of `@krizaka/app-client`;
21//! - the native menu bar the page describes in its own words ([`krizaka_rust::menu::MenuSpec`]), clicks sent back
22//!   as [`MENU`];
23//! - deep links (`<scheme>://…` and the product's web links) turned into a route ([`OPEN`], and [`take_links`] for the
24//!   ones that arrived before the page listened);
25//! - the navigation guard on every window: the app's own places stay, web links open in the browser, the rest is refused;
26//! - the update channel (`stable` / `beta`) and the feed it reads.
27
28mod commands;
29mod error;
30mod menu;
31mod watch;
32
33pub use krizaka_rust as kit;
34/// The folder picker the kit's commands open. The app registers it next to the kit —
35/// `.plugin(tauri_plugin_krizaka::dialog::init())` — and needs no dependency of its own: a plugin registered from inside
36/// another plugin's setup deadlocks Tauri's plugin store (found running the first app).
37pub use tauri_plugin_dialog as dialog;
38
39use krizaka_rust::access::Access;
40use krizaka_rust::deep_link::{self, LinkRules};
41use krizaka_rust::nav_guard::{self, Navigation};
42use krizaka_rust::scope::{ScopeStore, ScopedPath};
43use krizaka_rust::secrets::{Checked, SecretStore};
44use std::collections::{HashMap, HashSet};
45use std::path::{Path, PathBuf};
46use std::sync::Mutex;
47use tauri::plugin::{Builder as PluginBuilder, TauriPlugin};
48use tauri::{AppHandle, DragDropEvent, Emitter, Manager, Runtime, State, WindowEvent};
49
50pub use commands::take_links;
51pub use error::{CommandError, CODES};
52
53/// Paths the system reports as dropped on a window, already allowed by the gate: `string[]`.
54pub const DROPPED: &str = "krizaka://dropped";
55/// Files are being dragged over a window (`true`), or no longer are (`false`): the page shows where to drop.
56pub const DRAGGING: &str = "krizaka://dragging";
57/// A deep link's route (`/app/rapports`): `string`.
58pub const OPEN: &str = "krizaka://open";
59/// The id of a menu item the person chose: `string`.
60pub const MENU: &str = "krizaka://menu";
61/// A watched folder whose content changed (debounced): its path, `string`.
62pub const FOLDER_CHANGED: &str = "krizaka://folder-changed";
63
64const SCOPE_FILE: &str = "scope.json";
65const PREFS_FILE: &str = "krizaka.json";
66
67/// The kit's state in the app. A product's own command reads it with [`KitExt::kit`].
68pub struct Kit {
69    access: Mutex<Access>,
70    secrets: Box<dyn SecretStore>,
71    links: LinkRules,
72    pending: Mutex<Vec<String>>,
73    hosted: Vec<String>,
74    /// The window that shows the hosted app: a link navigates it (its page cannot listen, it has no IPC).
75    hosted_window: Option<String>,
76    update_feed: Option<String>,
77    data_dir: PathBuf,
78    menu_ids: Mutex<HashSet<String>>,
79    watches: Mutex<HashMap<PathBuf, watch::Watch>>,
80}
81
82impl Kit {
83    /// The one gate for a product's own command: a file of a granted folder, or a file dropped this session. Read it with
84    /// [`ScopedPath::open`], which confirms the opened file is still the one resolved.
85    pub fn resolve(&self, path: &Path) -> Result<ScopedPath, CommandError> {
86        Ok(error::lock(&self.access)?.resolve(path)?)
87    }
88
89    fn scope_file(&self) -> PathBuf {
90        self.data_dir.join(SCOPE_FILE)
91    }
92
93    fn prefs_file(&self) -> PathBuf {
94        self.data_dir.join(PREFS_FILE)
95    }
96}
97
98/// `app.kit()` (or `window.kit()`) in a product's command.
99pub trait KitExt<R: Runtime> {
100    fn kit(&self) -> State<'_, Kit>;
101}
102
103impl<R: Runtime, T: Manager<R>> KitExt<R> for T {
104    fn kit(&self) -> State<'_, Kit> {
105        self.state::<Kit>()
106    }
107}
108
109/// The plugin, configured with the product's own addresses.
110pub struct Builder {
111    scheme: String,
112    hosts: Vec<String>,
113    prefixes: Vec<String>,
114    hosted: Vec<String>,
115    hosted_window: Option<String>,
116    update_feed: Option<String>,
117}
118
119impl Builder {
120    /// `scheme` is the product's deep-link scheme, lowercase (`verikora`), the one its Info.plist declares.
121    pub fn new(scheme: &str) -> Self {
122        Builder {
123            scheme: scheme.to_ascii_lowercase(),
124            hosts: vec![],
125            prefixes: vec![],
126            hosted: vec![],
127            hosted_window: None,
128            update_feed: None,
129        }
130    }
131
132    /// The product's web hosts whose links open the app (`www.verikora.com`).
133    pub fn link_hosts<I: IntoIterator<Item = S>, S: Into<String>>(mut self, hosts: I) -> Self {
134        self.hosts = hosts.into_iter().map(Into::into).collect();
135        self
136    }
137
138    /// The routes a link may open (`/app`); none means every route.
139    pub fn link_prefixes<I: IntoIterator<Item = S>, S: Into<String>>(
140        mut self,
141        prefixes: I,
142    ) -> Self {
143        self.prefixes = prefixes.into_iter().map(Into::into).collect();
144        self
145    }
146
147    /// A hosted web app a window of this app may show (`https://www.folioviv.com`): HTTPS, reduced to its origin.
148    pub fn hosted_origin(mut self, origin: &str) -> Self {
149        self.hosted.push(origin.to_string());
150        self
151    }
152
153    /// The window (its label) that shows the first hosted origin: a deep link navigates it to the link's route on that
154    /// origin. A hosted page gets no capability, so it is told nothing; the window just goes there.
155    pub fn hosted_window(mut self, label: &str) -> Self {
156        self.hosted_window = Some(label.to_string());
157        self
158    }
159
160    /// The update feed, with `{channel}` (see [`krizaka_rust::update::feed_url`]). The app's `plugins.updater` must
161    /// then hold a `pubkey`, or the plugin refuses to start (see [`krizaka_rust::update`]).
162    pub fn update_feed(mut self, template: &str) -> Self {
163        self.update_feed = Some(template.to_string());
164        self
165    }
166
167    pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
168        let Builder {
169            scheme,
170            hosts,
171            prefixes,
172            hosted,
173            hosted_window,
174            update_feed,
175        } = self;
176        PluginBuilder::<R>::new("krizaka")
177            .invoke_handler(tauri::generate_handler![
178                commands::folders,
179                commands::grant_folder,
180                commands::revoke_folder,
181                commands::list_folder,
182                commands::watch_folder,
183                commands::unwatch_folder,
184                commands::secret_get,
185                commands::secret_set,
186                commands::secret_remove,
187                commands::set_menu,
188                commands::take_links,
189                commands::update_channel,
190                commands::set_update_channel,
191            ])
192            .setup(move |app, _api| {
193                let updater = app.config().plugins.0.get("updater");
194                if update_feed.is_some() || updater.is_some() {
195                    krizaka_rust::update::require_pubkey(updater)?;
196                }
197                if let Some(template) = &update_feed {
198                    krizaka_rust::update::feed_url(template, Default::default())?;
199                }
200                let hosted = hosted
201                    .iter()
202                    .map(|o| nav_guard::normalize_origin(o))
203                    .collect::<Result<Vec<_>, _>>()?;
204                let data_dir = app.path().app_data_dir()?;
205                let scope = ScopeStore::load(&data_dir.join(SCOPE_FILE));
206                app.manage(Kit {
207                    access: Mutex::new(Access::new(scope)),
208                    secrets: Box::new(Checked(krizaka_rust::keychain::Keychain::new(
209                        &app.config().identifier,
210                    ))),
211                    links: LinkRules {
212                        scheme,
213                        hosts,
214                        prefixes,
215                    },
216                    pending: Mutex::new(vec![]),
217                    hosted,
218                    hosted_window,
219                    update_feed,
220                    data_dir,
221                    menu_ids: Mutex::new(HashSet::new()),
222                    watches: Mutex::new(HashMap::new()),
223                });
224                app.on_menu_event(|app, event| menu::clicked(app, event.id().as_ref()));
225                Ok(())
226            })
227            .on_navigation(|webview, url| {
228                let mut places = own_places(webview.app_handle());
229                if let Some(kit) = webview.try_state::<Kit>() {
230                    places.extend(kit.hosted.iter().cloned());
231                }
232                match nav_guard::decide(&places, url) {
233                    Navigation::Stay => true,
234                    Navigation::Browser => {
235                        open_in_browser(url.as_str());
236                        false
237                    }
238                    Navigation::Refuse => false,
239                }
240            })
241            .on_window_ready(|window| {
242                let target = window.clone();
243                window.on_window_event(move |event| {
244                    match event {
245                        WindowEvent::DragDrop(DragDropEvent::Enter { .. }) => {
246                            let _ = target.emit_to(target.label(), DRAGGING, true);
247                        }
248                        WindowEvent::DragDrop(DragDropEvent::Leave) => {
249                            let _ = target.emit_to(target.label(), DRAGGING, false);
250                        }
251                        _ => {}
252                    }
253                    if let WindowEvent::DragDrop(DragDropEvent::Drop { paths, .. }) = event {
254                        let _ = target.emit_to(target.label(), DRAGGING, false);
255                        let allowed: Vec<String> = {
256                            let kit = target.kit();
257                            let mut access = match kit.access.lock() {
258                                Ok(a) => a,
259                                Err(_) => return,
260                            };
261                            paths
262                                .iter()
263                                .filter_map(|p| access.allow_dropped(p))
264                                .map(|p| p.display().to_string())
265                                .collect()
266                        };
267                        let _ = target.emit_to(target.label(), DROPPED, allowed);
268                    }
269                });
270            })
271            .on_event(|_app, _event| {
272                #[cfg(target_os = "macos")]
273                if let tauri::RunEvent::Opened { urls } = _event {
274                    opened(_app, urls.iter().map(|u| u.as_str()));
275                }
276            })
277            .build()
278    }
279}
280
281/// The app's own local page, and its dev server while debugging.
282fn own_places<R: Runtime>(app: &AppHandle<R>) -> Vec<String> {
283    let mut places = vec![
284        "tauri://localhost".to_string(),
285        "http://tauri.localhost".to_string(),
286    ];
287    if cfg!(debug_assertions) {
288        if let Some(dev) = &app.config().build.dev_url {
289            places.push(dev.as_str().to_string());
290        }
291    }
292    places
293}
294
295fn open_in_browser(url: &str) {
296    #[cfg(target_os = "macos")]
297    {
298        let _ = std::process::Command::new("open").arg(url).spawn();
299    }
300    #[cfg(not(target_os = "macos"))]
301    let _ = url;
302}
303
304/// Links the system opened the app with: each becomes a route sent to the page (and kept until it takes them), the window
305/// comes forward; a link that is not the product's is dropped.
306fn opened<'a, R: Runtime>(app: &AppHandle<R>, urls: impl Iterator<Item = &'a str>) {
307    let Some(kit) = app.try_state::<Kit>() else {
308        return;
309    };
310    let routes: Vec<String> = urls
311        .filter_map(|u| deep_link::route(&kit.links, u).ok())
312        .collect();
313    if routes.is_empty() {
314        return;
315    }
316    if let Ok(mut pending) = kit.pending.lock() {
317        pending.extend(routes.iter().cloned());
318    }
319    let hosted = kit
320        .hosted_window
321        .as_ref()
322        .and_then(|label| Some((app.get_webview_window(label)?, kit.hosted.first()?.clone())));
323    if let Some(window) = hosted
324        .as_ref()
325        .map(|(w, _)| w.clone())
326        .or_else(|| app.webview_windows().into_values().next())
327    {
328        let _ = window.unminimize();
329        let _ = window.show();
330        let _ = window.set_focus();
331    }
332    if let (Some((window, origin)), Some(last)) = (&hosted, routes.last()) {
333        if let Ok(target) = url::Url::parse(origin).and_then(|o| o.join(last)) {
334            let _ = window.navigate(target);
335        }
336    }
337    for route in routes {
338        let _ = app.emit(OPEN, route);
339    }
340}
341
342/// Sets the menu bar from Rust, for an app whose page cannot send it (a hosted app): the same checks as the command.
343pub fn set_menu<R: Runtime>(
344    app: &AppHandle<R>,
345    spec: &krizaka_rust::menu::MenuSpec,
346) -> Result<(), CommandError> {
347    commands::apply_menu(app, &app.kit(), spec)
348}