Refactor using Tauri (#278)

This commit is contained in:
Kevin Yue
2024-01-16 22:18:20 +08:00
committed by GitHub
parent edc13ed14d
commit 04a916a3e1
199 changed files with 10153 additions and 7203 deletions

View File

@@ -0,0 +1,21 @@
use base64::{engine::general_purpose, Engine};
pub fn encode(data: &[u8]) -> String {
let engine = general_purpose::STANDARD;
engine.encode(data)
}
pub fn decode_to_vec(s: &str) -> anyhow::Result<Vec<u8>> {
let engine = general_purpose::STANDARD;
let decoded = engine.decode(s)?;
Ok(decoded)
}
pub(crate) fn decode_to_string(s: &str) -> anyhow::Result<String> {
let decoded = decode_to_vec(s)?;
let decoded = String::from_utf8(decoded)?;
Ok(decoded)
}

View File

@@ -0,0 +1,108 @@
use chacha20poly1305::{
aead::{Aead, OsRng},
AeadCore, ChaCha20Poly1305, Key, KeyInit, Nonce,
};
use serde::{de::DeserializeOwned, Serialize};
pub fn generate_key() -> Key {
ChaCha20Poly1305::generate_key(&mut OsRng)
}
pub fn encrypt<T>(key: &Key, value: &T) -> anyhow::Result<Vec<u8>>
where
T: Serialize,
{
let cipher = ChaCha20Poly1305::new(key);
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
let data = serde_json::to_vec(value)?;
let cipher_text = cipher.encrypt(&nonce, data.as_ref())?;
let mut encrypted = Vec::new();
encrypted.extend_from_slice(&nonce);
encrypted.extend_from_slice(&cipher_text);
Ok(encrypted)
}
pub fn decrypt<T>(key: &Key, encrypted: Vec<u8>) -> anyhow::Result<T>
where
T: DeserializeOwned,
{
let cipher = ChaCha20Poly1305::new(key);
let nonce = Nonce::from_slice(&encrypted[..12]);
let cipher_text = &encrypted[12..];
let plaintext = cipher.decrypt(nonce, cipher_text)?;
let value = serde_json::from_slice(&plaintext)?;
Ok(value)
}
pub struct Crypto {
key: Vec<u8>,
}
impl Crypto {
pub fn new(key: Vec<u8>) -> Self {
Self { key }
}
pub fn encrypt<T: Serialize>(&self, plain: T) -> anyhow::Result<Vec<u8>> {
let key: &[u8] = &self.key;
let encrypted_data = encrypt(key.into(), &plain)?;
Ok(encrypted_data)
}
pub fn decrypt<T: DeserializeOwned>(&self, encrypted: Vec<u8>) -> anyhow::Result<T> {
let key: &[u8] = &self.key;
decrypt(key.into(), encrypted)
}
pub fn encrypt_to<T: Serialize>(&self, path: &std::path::Path, plain: T) -> anyhow::Result<()> {
let encrypted_data = self.encrypt(plain)?;
std::fs::write(path, encrypted_data)?;
Ok(())
}
pub fn decrypt_from<T: DeserializeOwned>(&self, path: &std::path::Path) -> anyhow::Result<T> {
let encrypted_data = std::fs::read(path)?;
self.decrypt(encrypted_data)
}
}
#[cfg(test)]
mod tests {
use serde::Deserialize;
use super::*;
#[derive(Serialize, Deserialize)]
struct User {
name: String,
age: u8,
}
#[test]
fn it_works() -> anyhow::Result<()> {
let key = generate_key();
let user = User {
name: "test".to_string(),
age: 18,
};
let encrypted = encrypt(&key, &user)?;
let decrypted_user = decrypt::<User>(&key, encrypted)?;
assert_eq!(user.name, decrypted_user.name);
assert_eq!(user.age, decrypted_user.age);
Ok(())
}
}

View File

@@ -0,0 +1,20 @@
use tokio::fs;
use crate::GP_SERVICE_LOCK_FILE;
async fn read_port() -> anyhow::Result<String> {
let port = fs::read_to_string(GP_SERVICE_LOCK_FILE).await?;
Ok(port.trim().to_string())
}
pub async fn http_endpoint() -> anyhow::Result<String> {
let port = read_port().await?;
Ok(format!("http://127.0.0.1:{}", port))
}
pub async fn ws_endpoint() -> anyhow::Result<String> {
let port = read_port().await?;
Ok(format!("ws://127.0.0.1:{}/ws", port))
}

View File

@@ -0,0 +1,37 @@
use std::collections::HashMap;
use std::env;
use std::io::Write;
use std::path::Path;
use tempfile::NamedTempFile;
pub fn persist_env_vars(extra: Option<HashMap<String, String>>) -> anyhow::Result<NamedTempFile> {
let mut env_file = NamedTempFile::new()?;
let content = env::vars()
.map(|(key, value)| format!("{}={}", key, value))
.chain(
extra
.unwrap_or_default()
.into_iter()
.map(|(key, value)| format!("{}={}", key, value)),
)
.collect::<Vec<String>>()
.join("\n");
writeln!(env_file, "{}", content)?;
Ok(env_file)
}
pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<String, String>> {
let content = std::fs::read_to_string(env_file)?;
let mut env_vars: HashMap<String, String> = HashMap::new();
for line in content.lines() {
if let Some((key, value)) = line.split_once('=') {
env_vars.insert(key.to_string(), value.to_string());
}
}
Ok(env_vars)
}

View File

@@ -0,0 +1,39 @@
use std::path::PathBuf;
pub struct LockFile {
path: PathBuf,
}
impl LockFile {
pub fn new<P: Into<PathBuf>>(path: P) -> Self {
Self { path: path.into() }
}
pub fn exists(&self) -> bool {
self.path.exists()
}
pub fn lock(&self, content: impl AsRef<[u8]>) -> anyhow::Result<()> {
std::fs::write(&self.path, content)?;
Ok(())
}
pub fn unlock(&self) -> anyhow::Result<()> {
std::fs::remove_file(&self.path)?;
Ok(())
}
pub async fn check_health(&self) -> bool {
match std::fs::read_to_string(&self.path) {
Ok(content) => {
let url = format!("http://127.0.0.1:{}/health", content.trim());
match reqwest::get(&url).await {
Ok(resp) => resp.status().is_success(),
Err(_) => false,
}
}
Err(_) => false,
}
}
}

View File

@@ -0,0 +1,40 @@
use reqwest::Url;
pub(crate) mod xml;
pub mod base64;
pub mod crypto;
pub mod endpoint;
pub mod env_file;
pub mod lock_file;
pub mod openssl;
pub mod redact;
#[cfg(feature = "tauri")]
pub mod window;
mod shutdown_signal;
pub use shutdown_signal::shutdown_signal;
/// Normalize the server URL to the format `https://<host>:<port>`
pub fn normalize_server(server: &str) -> anyhow::Result<String> {
let server = if server.starts_with("https://") || server.starts_with("http://") {
server.to_string()
} else {
format!("https://{}", server)
};
let normalized_url = Url::parse(&server)?;
let scheme = normalized_url.scheme();
let host = normalized_url
.host_str()
.ok_or(anyhow::anyhow!("Invalid server URL: missing host"))?;
let port: String = normalized_url
.port()
.map_or("".into(), |port| format!(":{}", port));
let normalized_url = format!("{}://{}{}", scheme, host, port);
Ok(normalized_url)
}

View File

@@ -0,0 +1,37 @@
use std::path::Path;
use tempfile::NamedTempFile;
pub fn openssl_conf() -> String {
let option = "UnsafeLegacyServerConnect";
format!(
"openssl_conf = openssl_init
[openssl_init]
ssl_conf = ssl_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
Options = {}",
option
)
}
pub fn fix_openssl<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
let content = openssl_conf();
std::fs::write(path, content)?;
Ok(())
}
pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
let openssl_conf = NamedTempFile::new()?;
let openssl_conf_path = openssl_conf.path();
fix_openssl(openssl_conf_path)?;
std::env::set_var("OPENSSL_CONF", openssl_conf_path);
Ok(openssl_conf)
}

View File

@@ -0,0 +1,227 @@
use std::sync::RwLock;
use redact_engine::{Pattern, Redaction as RedactEngine};
use regex::Regex;
use url::{form_urlencoded, Url};
pub struct Redaction {
redact_engine: RwLock<Option<RedactEngine>>,
}
impl Default for Redaction {
fn default() -> Self {
Self::new()
}
}
impl Redaction {
pub fn new() -> Self {
let redact_engine = RedactEngine::custom("[**********]").add_pattern(Pattern {
test: Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
group: 1,
});
Self {
redact_engine: RwLock::new(Some(redact_engine)),
}
}
pub fn add_value(&self, text: &str) -> anyhow::Result<()> {
let mut redact_engine = self
.redact_engine
.write()
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
*redact_engine = Some(
redact_engine
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
.add_value(text)?,
);
Ok(())
}
pub fn add_values(&self, texts: &[&str]) -> anyhow::Result<()> {
let mut redact_engine = self
.redact_engine
.write()
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
*redact_engine = Some(
redact_engine
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
.add_values(texts.to_vec())?,
);
Ok(())
}
pub fn redact_str(&self, text: &str) -> String {
self
.redact_engine
.read()
.expect("Failed to acquire read lock on redact engine")
.as_ref()
.expect("Failed to get redact engine")
.redact_str(text)
}
}
/// Redact a value by replacing all but the first and last character with asterisks,
/// The length of the value to be redacted must be at least 3 characters.
/// e.g. "foo" -> "f**********o"
pub fn redact_value(text: &str) -> String {
if text.len() < 3 {
return text.to_string();
}
let mut redacted = String::new();
redacted.push_str(&text[0..1]);
redacted.push_str(&"*".repeat(10));
redacted.push_str(&text[text.len() - 1..]);
redacted
}
pub fn redact_uri(uri: &str) -> String {
let Ok(mut url) = Url::parse(uri) else {
return uri.to_string();
};
// Could be a data: URI
if url.cannot_be_a_base() {
if url.scheme() == "about" {
return uri.to_string();
}
if url.path().len() > 15 {
return format!(
"{}:{}{}",
url.scheme(),
&url.path()[0..10],
redact_value(&url.path()[10..])
);
}
return format!("{}:{}", url.scheme(), redact_value(url.path()));
}
let host = url.host_str().unwrap_or_default();
if url.set_host(Some(&redact_value(host))).is_err() {
let redacted_query = redact_query(url.query())
.as_deref()
.map(|query| format!("?{}", query))
.unwrap_or_default();
return format!(
"{}://[**********]{}{}",
url.scheme(),
url.path(),
redacted_query
);
}
let redacted_query = redact_query(url.query());
url.set_query(redacted_query.as_deref());
url.to_string()
}
fn redact_query(query: Option<&str>) -> Option<String> {
let query = query?;
let query_pairs = form_urlencoded::parse(query.as_bytes());
let mut redacted_pairs = query_pairs.map(|(key, value)| (key, redact_value(&value)));
let query = form_urlencoded::Serializer::new(String::new())
.extend_pairs(redacted_pairs.by_ref())
.finish();
Some(query)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_should_not_redact_value() {
let text = "fo";
assert_eq!(redact_value(text), "fo");
}
#[test]
fn it_should_redact_value() {
let text = "foo";
assert_eq!(redact_value(text), "f**********o");
}
#[test]
fn it_should_redact_dynamic_value() {
let redaction = Redaction::new();
redaction.add_value("foo").unwrap();
assert_eq!(
redaction.redact_str("hello, foo, bar"),
"hello, [**********], bar"
);
}
#[test]
fn it_should_redact_dynamic_values() {
let redaction = Redaction::new();
redaction.add_values(&["foo", "bar"]).unwrap();
assert_eq!(
redaction.redact_str("hello, foo, bar"),
"hello, [**********], [**********]"
);
}
#[test]
fn it_should_redact_uri() {
let uri = "https://foo.bar";
assert_eq!(redact_uri(uri), "https://f**********r/");
let uri = "https://foo.bar/";
assert_eq!(redact_uri(uri), "https://f**********r/");
let uri = "https://foo.bar/baz";
assert_eq!(redact_uri(uri), "https://f**********r/baz");
let uri = "https://foo.bar/baz?qux=quux";
assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x");
}
#[test]
fn it_should_redact_data_uri() {
let uri = "data:text/plain;a";
assert_eq!(redact_uri(uri), "data:t**********a");
let uri = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==";
assert_eq!(redact_uri(uri), "data:text/plain;**********=");
let uri = "about:blank";
assert_eq!(redact_uri(uri), "about:blank");
}
#[test]
fn it_should_redact_ipv6() {
let uri = "https://[2001:db8::1]:8080";
assert_eq!(redact_uri(uri), "https://[**********]/");
let uri = "https://[2001:db8::1]:8080/";
assert_eq!(redact_uri(uri), "https://[**********]/");
let uri = "https://[2001:db8::1]:8080/baz";
assert_eq!(redact_uri(uri), "https://[**********]/baz");
let uri = "https://[2001:db8::1]:8080/baz?qux=quux";
assert_eq!(redact_uri(uri), "https://[**********]/baz?qux=q**********x");
}
}

View File

@@ -0,0 +1,22 @@
use tokio::signal;
pub async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}

View File

@@ -0,0 +1,90 @@
use std::{process::ExitStatus, time::Duration};
use anyhow::bail;
use log::{info, warn};
use tauri::{window::MenuHandle, Window};
use tokio::process::Command;
pub trait WindowExt {
fn raise(&self) -> anyhow::Result<()>;
}
impl WindowExt for Window {
fn raise(&self) -> anyhow::Result<()> {
raise_window(self)
}
}
pub fn raise_window(win: &Window) -> anyhow::Result<()> {
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland {
win.hide()?;
win.show()?;
} else {
if !win.is_visible()? {
win.show()?;
}
let title = win.title()?;
tokio::spawn(async move {
info!("Raising window: {}", title);
if let Err(err) = wmctrl_raise_window(&title).await {
warn!("Failed to raise window: {}", err);
}
});
}
// Calling window.show() on Windows will cause the menu to be shown.
hide_menu(win.menu_handle());
Ok(())
}
async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> {
let mut counter = 0;
loop {
if let Ok(exit_status) = wmctrl_try_raise_window(title).await {
if exit_status.success() {
info!("Window raised after {} attempts", counter + 1);
return Ok(());
}
}
if counter >= 10 {
bail!("Failed to raise window: {}", title)
}
counter += 1;
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> {
let exit_status = Command::new("wmctrl")
.arg("-F")
.arg("-a")
.arg(title)
.spawn()?
.wait()
.await?;
Ok(exit_status)
}
fn hide_menu(menu_handle: MenuHandle) {
tokio::spawn(async move {
loop {
let menu_visible = menu_handle.is_visible().unwrap_or(false);
if !menu_visible {
break;
}
if menu_visible {
let _ = menu_handle.hide();
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
});
}

View File

@@ -0,0 +1,6 @@
use roxmltree::Document;
pub(crate) fn get_child_text(doc: &Document, name: &str) -> Option<String> {
let node = doc.descendants().find(|n| n.has_tag_name(name))?;
node.text().map(|s| s.to_string())
}