Преглед на файлове

refactor(tauri): move static salts into manager instance (#1426)

chip преди 4 години
родител
ревизия
43589c9b8c
променени са 7 файла, в които са добавени 53 реда и са изтрити 65 реда
  1. 6 2
      tauri/src/endpoints.rs
  2. 3 7
      tauri/src/endpoints/internal.rs
  3. 0 2
      tauri/src/lib.rs
  4. 32 0
      tauri/src/runtime/manager.rs
  5. 7 0
      tauri/src/runtime/mod.rs
  6. 5 1
      tauri/src/runtime/window.rs
  7. 0 53
      tauri/src/salt.rs

+ 6 - 2
tauri/src/endpoints.rs

@@ -67,8 +67,12 @@ impl Module {
           .and_then(|r| r.json)
           .map_err(|e| e.to_string())
       }),
-      Self::Internal(cmd) => message
-        .respond_async(async move { cmd.run().and_then(|r| r.json).map_err(|e| e.to_string()) }),
+      Self::Internal(cmd) => message.respond_async(async move {
+        cmd
+          .run(window)
+          .and_then(|r| r.json)
+          .map_err(|e| e.to_string())
+      }),
       Self::Dialog(cmd) => message
         .respond_async(async move { cmd.run().and_then(|r| r.json).map_err(|e| e.to_string()) }),
       Self::Cli(cmd) => {

+ 3 - 7
tauri/src/endpoints/internal.rs

@@ -1,4 +1,5 @@
 use super::InvokeResponse;
+use crate::{runtime::window::Window, Params};
 use serde::Deserialize;
 
 /// The API descriptor.
@@ -9,14 +10,9 @@ pub enum Cmd {
 }
 
 impl Cmd {
-  pub fn run(self) -> crate::Result<InvokeResponse> {
+  pub fn run<P: Params>(self, window: Window<P>) -> crate::Result<InvokeResponse> {
     match self {
-      Self::ValidateSalt { salt } => validate_salt(salt),
+      Self::ValidateSalt { salt } => Ok(window.verify_salt(salt).into()),
     }
   }
 }
-
-/// Validates a salt.
-pub fn validate_salt(salt: String) -> crate::Result<InvokeResponse> {
-  Ok(crate::salt::is_valid(salt).into())
-}

+ 0 - 2
tauri/src/lib.rs

@@ -24,8 +24,6 @@ mod hooks;
 pub mod plugin;
 /// The internal runtime between an [`App`] and the webview.
 pub mod runtime;
-/// The salt helpers.
-mod salt;
 
 /// Tauri result type.
 pub type Result<T> = std::result::Result<T, Error>;

+ 32 - 0
tauri/src/runtime/manager.rs

@@ -25,6 +25,7 @@ use std::{
   convert::TryInto,
   sync::{Arc, Mutex},
 };
+use uuid::Uuid;
 
 pub struct InnerWindowManager<M: Params> {
   windows: Mutex<HashSet<Window<M>>>,
@@ -40,6 +41,9 @@ pub struct InnerWindowManager<M: Params> {
   config: Config,
   assets: Arc<M::Assets>,
   default_window_icon: Option<Vec<u8>>,
+
+  /// A list of salts that are valid for the current application.
+  salts: Mutex<HashSet<Uuid>>,
 }
 
 pub struct WindowManager<E, L, A, R>
@@ -88,6 +92,7 @@ where
         config: context.config,
         assets: Arc::new(context.assets),
         default_window_icon: context.default_window_icon,
+        salts: Mutex::default(),
       }),
     }
   }
@@ -511,6 +516,33 @@ where
   fn event_emit_function_name(&self) -> String {
     self.inner.listeners.function_name()
   }
+
+  fn generate_salt(&self) -> Uuid {
+    let salt = Uuid::new_v4();
+    self
+      .inner
+      .salts
+      .lock()
+      .expect("poisoned salt mutex")
+      .insert(salt);
+    salt
+  }
+
+  fn verify_salt(&self, salt: String) -> bool {
+    // flat out ignore any invalid uuids
+    let uuid: Uuid = match salt.parse() {
+      Ok(uuid) => uuid,
+      Err(_) => return false,
+    };
+
+    // HashSet::remove lets us know if the entry was found
+    self
+      .inner
+      .salts
+      .lock()
+      .expect("poisoned salt mutex")
+      .remove(&uuid)
+  }
 }
 
 impl<E, L, A, R> Params for WindowManager<E, L, A, R>

+ 7 - 0
tauri/src/runtime/mod.rs

@@ -149,6 +149,7 @@ pub(crate) mod sealed {
   };
   use serde::Serialize;
   use std::collections::HashSet;
+  use uuid::Uuid;
 
   /// private manager api
   pub trait ParamsPrivate<M: Params>: Clone + Send + Sized + 'static {
@@ -225,6 +226,12 @@ pub(crate) mod sealed {
     fn event_listeners_object_name(&self) -> String;
     fn event_queue_object_name(&self) -> String;
     fn event_emit_function_name(&self) -> String;
+
+    /// Generate a random salt and store it in the manager
+    fn generate_salt(&self) -> Uuid;
+
+    /// Verify that the passed salt is a valid salt in the manager.
+    fn verify_salt(&self, salt: String) -> bool;
   }
 
   /// Represents a managed handle to the application runner.

+ 5 - 1
tauri/src/runtime/window.rs

@@ -182,7 +182,7 @@ impl<M: Params> Window<M> {
       self.manager.event_emit_function_name(),
       event.to_javascript()?,
       js_payload,
-      crate::salt::generate()
+      self.manager.generate_salt(),
     ))?;
 
     Ok(())
@@ -361,4 +361,8 @@ impl<M: Params> Window<M> {
   pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
     self.window.dispatcher.set_icon(icon.try_into()?)
   }
+
+  pub(crate) fn verify_salt(&self, salt: String) -> bool {
+    self.manager.verify_salt(salt)
+  }
 }

+ 0 - 53
tauri/src/salt.rs

@@ -1,53 +0,0 @@
-use std::sync::Mutex;
-
-use once_cell::sync::Lazy;
-use uuid::Uuid;
-
-/// A salt definition.
-struct Salt {
-  value: String,
-  one_time: bool,
-}
-
-static SALTS: Lazy<Mutex<Vec<Salt>>> = Lazy::new(Mutex::default);
-
-/// Generates a one time Salt and returns its string representation.
-pub fn generate() -> String {
-  let salt = Uuid::new_v4();
-  SALTS
-    .lock()
-    .expect("Failed to lock Salt mutex: generate()")
-    .push(Salt {
-      value: salt.to_string(),
-      one_time: true,
-    });
-  salt.to_string()
-}
-
-/// Generates a static Salt and returns its string representation.
-#[allow(dead_code)]
-pub fn generate_static() -> String {
-  let salt = Uuid::new_v4();
-  SALTS
-    .lock()
-    .expect("Failed to lock SALT mutex: generate_static()")
-    .push(Salt {
-      value: salt.to_string(),
-      one_time: false,
-    });
-  salt.to_string()
-}
-
-/// Checks if the given Salt representation is valid.
-pub fn is_valid(salt: String) -> bool {
-  let mut salts = SALTS.lock().expect("Failed to lock Salt mutex: is_valid()");
-  match salts.iter().position(|s| s.value == salt) {
-    Some(index) => {
-      if salts[index].one_time {
-        salts.remove(index);
-      }
-      true
-    }
-    None => false,
-  }
-}