Przeglądaj źródła

feat(core): inject invoke key in custom invoke system script (#11025)

* feat(core): inject invoke key in custom invoke system script

* fix fmt
Lucas Fernandes Nogueira 10 miesięcy temu
rodzic
commit
e7fd676c27

+ 5 - 0
.changes/custom-invoke-system-invoke-key.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch:enhance
+---
+
+Inject `__INVOKE_KEY__` into custom invoke systems so their implementations can properly construct `tauri::webview::InvokeRequest`.

+ 1 - 1
Cargo.lock

@@ -7284,7 +7284,7 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
 
 [[package]]
 name = "tauri"
-version = "2.0.0-rc.13"
+version = "2.0.0-rc.14"
 dependencies = [
  "anyhow",
  "bytes",

+ 16 - 1
crates/tauri/src/app.rs

@@ -1316,12 +1316,27 @@ impl<R: Runtime> Builder<R> {
   ///
   /// The `initialization_script` is a script that initializes `window.__TAURI_INTERNALS__.postMessage`.
   /// That function must take the `(message: object, options: object)` arguments and send it to the backend.
+  ///
+  /// Additionally, the script must include a `__INVOKE_KEY__` token that is replaced with a value that must be sent with the IPC payload
+  /// to check the integrity of the message by the [`crate::WebviewWindow::on_message`] API, e.g.
+  ///
+  /// ```js
+  /// const invokeKey = __INVOKE_KEY__;
+  /// fetch('my-impl://command', {
+  ///   headers: {
+  ///     'Tauri-Invoke-Key': invokeKey,
+  ///   }
+  /// })
+  /// ```
+  ///
+  /// Note that the implementation details is up to your implementation.
   #[must_use]
   pub fn invoke_system<F>(mut self, initialization_script: String, responder: F) -> Self
   where
     F: Fn(&Webview<R>, &str, &InvokeResponse, CallbackFn, CallbackFn) + Send + Sync + 'static,
   {
-    self.invoke_initialization_script = initialization_script;
+    self.invoke_initialization_script =
+      initialization_script.replace("__INVOKE_KEY__", &format!("\"{}\"", self.invoke_key));
     self.invoke_responder.replace(Arc::new(responder));
     self
   }

+ 1 - 3
crates/tauri/src/webview/mod.rs

@@ -115,10 +115,8 @@ impl<'a> PageLoadPayload<'a> {
 /// # Stability
 ///
 /// This struct is **NOT** part of the public stable API and is only meant to be used
-/// by internal code and external testing/fuzzing tools. If not used with feature `unstable`, this
-/// struct is marked `#[non_exhaustive]` and is non-constructable externally.
+/// by internal code and external testing/fuzzing tools or custom invoke systems.
 #[derive(Debug)]
-#[cfg_attr(not(feature = "test"), non_exhaustive)]
 pub struct InvokeRequest {
   /// The invoke command.
   pub cmd: String,