Connection re-use for plugin networking and beta NTLM plugin (#295)

This commit is contained in:
Gregory Schier
2025-11-10 14:41:49 -08:00
committed by GitHub
parent d318546d0c
commit 6389fd3b8f
48 changed files with 941 additions and 554 deletions

72
src-tauri/Cargo.lock generated
View File

@@ -2790,7 +2790,7 @@ dependencies = [
"dbus-secret-service",
"log",
"security-framework 2.11.1",
"security-framework 3.2.0",
"security-framework 3.5.1",
"windows-sys 0.60.2",
"zeroize",
]
@@ -3009,9 +3009,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.27"
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
dependencies = [
"value-bag",
]
@@ -4763,9 +4763,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.33"
version = "0.23.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "751e04a496ca00bb97a5e043158d23d66b5aabf2e1d5aa2a0aaebb1aafe6f82c"
checksum = "6a9586e9ee2b4f8fab52a0048ca7334d7024eef48e2cb9407e3497bb7cab7fa7"
dependencies = [
"once_cell",
"ring",
@@ -4784,7 +4784,7 @@ dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework 3.2.0",
"security-framework 3.5.1",
]
[[package]]
@@ -4799,9 +4799,9 @@ dependencies = [
[[package]]
name = "rustls-platform-verifier"
version = "0.6.1"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be59af91596cac372a6942530653ad0c3a246cdd491aaa9dcaee47f88d67d5a0"
checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
@@ -4812,10 +4812,10 @@ dependencies = [
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework 3.2.0",
"security-framework 3.5.1",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4963,9 +4963,9 @@ dependencies = [
[[package]]
name = "security-framework"
version = "3.2.0"
version = "3.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316"
checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef"
dependencies = [
"bitflags 2.9.1",
"core-foundation 0.10.1",
@@ -4976,9 +4976,9 @@ dependencies = [
[[package]]
name = "security-framework-sys"
version = "2.14.0"
version = "2.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32"
checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"
dependencies = [
"core-foundation-sys",
"libc",
@@ -5620,9 +5620,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "tauri"
version = "2.9.0"
version = "2.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f07c6590706b2fc0ab287b041cf5ce9c435b3850bdae5571e19d9d27584e89d"
checksum = "8bceb52453e507c505b330afe3398510e87f428ea42b6e76ecb6bd63b15965b5"
dependencies = [
"anyhow",
"bytes",
@@ -5664,7 +5664,6 @@ dependencies = [
"tokio",
"tray-icon",
"url",
"urlpattern",
"webkit2gtk",
"webview2-com",
"window-vibrancy",
@@ -5673,9 +5672,9 @@ dependencies = [
[[package]]
name = "tauri-build"
version = "2.5.0"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f71be1f494b683ac439e6d61c16ab5c472c6f9c6ee78995b29556d9067c021a1"
checksum = "a924b6c50fe83193f0f8b14072afa7c25b7a72752a2a73d9549b463f5fe91a38"
dependencies = [
"anyhow",
"cargo_toml",
@@ -5736,9 +5735,9 @@ dependencies = [
[[package]]
name = "tauri-plugin"
version = "2.5.0"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7ce9aab979296b2f91e6fbf154207c2e3512b12ddca0b24bfa0e0cde6b2976"
checksum = "076c78a474a7247c90cad0b6e87e593c4c620ed4efdb79cbe0214f0021f6c39d"
dependencies = [
"anyhow",
"glob",
@@ -5789,9 +5788,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-dialog"
version = "2.4.0"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0beee42a4002bc695550599b011728d9dfabf82f767f134754ed6655e434824e"
checksum = "313f8138692ddc4a2127c4c9607d616a46f5c042e77b3722450866da0aad2f19"
dependencies = [
"log",
"raw-window-handle",
@@ -5807,9 +5806,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-fs"
version = "2.4.2"
version = "2.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "315784ec4be45e90a987687bae7235e6be3d6e9e350d2b75c16b8a4bf22c1db7"
checksum = "47df422695255ecbe7bac7012440eddaeefd026656171eac9559f5243d3230d9"
dependencies = [
"anyhow",
"dunce",
@@ -5891,9 +5890,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-shell"
version = "2.3.1"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54777d0c0d8add34eea3ced84378619ef5b97996bd967d3038c668feefd21071"
checksum = "c374b6db45f2a8a304f0273a15080d98c70cde86178855fc24653ba657a1144c"
dependencies = [
"encoding_rs",
"log",
@@ -5975,9 +5974,9 @@ dependencies = [
[[package]]
name = "tauri-runtime"
version = "2.9.0"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3367f0b47df90e9195cd9f04a56b0055a2cba45aa11923c6c253d748778176fc"
checksum = "9368f09358496f2229313fccb37682ad116b7f46fa76981efe116994a0628926"
dependencies = [
"cookie",
"dpi",
@@ -6000,9 +5999,9 @@ dependencies = [
[[package]]
name = "tauri-runtime-wry"
version = "2.9.0"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80d91d29ca680c545364cf75ba2f2e3c7ea2ab6376bfa3be26b56fa2463a5b5e"
checksum = "929f5df216f5c02a9e894554401bcdab6eec3e39ec6a4a7731c7067fc8688a93"
dependencies = [
"gtk",
"http",
@@ -7816,7 +7815,6 @@ dependencies = [
"cookie",
"eventsource-client",
"http",
"hyper-util",
"log",
"md5 0.8.0",
"mime_guess",
@@ -7842,7 +7840,6 @@ dependencies = [
"thiserror 2.0.17",
"tokio",
"tokio-stream",
"tower-service",
"ts-rs",
"uuid",
"yaak-common",
@@ -7948,9 +7945,18 @@ dependencies = [
name = "yaak-http"
version = "0.1.0"
dependencies = [
"hyper-util",
"log",
"regex",
"reqwest",
"reqwest_cookie_store",
"rustls",
"rustls-platform-verifier",
"serde",
"tauri",
"thiserror 2.0.17",
"tokio",
"tower-service",
"urlencoding",
"yaak-models",
]

View File

@@ -48,7 +48,7 @@ chrono = { workspace = true, features = ["serde"] }
cookie = "0.18.1"
eventsource-client = { git = "https://github.com/yaakapp/rust-eventsource-client", version = "0.14.0" }
http = { version = "1.2.0", default-features = false }
log = "0.4.27"
log = { workspace = true }
md5 = "0.8.0"
mime_guess = "2.0.5"
rand = "0.9.0"
@@ -68,8 +68,6 @@ tauri-plugin-shell = { workspace = true }
tauri-plugin-single-instance = { version = "2.3.4", features = ["deep-link"] }
tauri-plugin-updater = "2.9.0"
tauri-plugin-window-state = "2.4.0"
hyper-util = { version = "0.1.17", default-features = false, features = ["client-legacy"] }
tower-service = "0.3.3"
thiserror = { workspace = true }
tokio = { workspace = true, features = ["sync"] }
tokio-stream = "0.1.17"
@@ -96,15 +94,16 @@ hex = "0.4.3"
keyring = "3.6.3"
reqwest = "0.12.20"
reqwest_cookie_store = "0.8.0"
rustls = { version = "0.23.33", default-features = false }
rustls-platform-verifier = "0.6.1"
rustls = { version = "0.23.34", default-features = false }
rustls-platform-verifier = "0.6.2"
serde = "1.0.228"
serde_json = "1.0.145"
sha2 = "0.10.9"
tauri = "2.9.0"
tauri-plugin = "2.5.0"
tauri-plugin-dialog = "2.4.0"
tauri-plugin-shell = "2.3.1"
log = "0.4.28"
tauri = "2.9.2"
tauri-plugin = "2.5.1"
tauri-plugin-dialog = "2.4.2"
tauri-plugin-shell = "2.3.3"
thiserror = "2.0.17"
tokio = "1.48.0"
ts-rs = "11.1.0"

View File

@@ -2,7 +2,7 @@ use crate::error::Result;
use tauri::{command, AppHandle, Manager, Runtime, State, WebviewWindow};
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
use yaak_crypto::manager::EncryptionManagerExt;
use yaak_plugins::events::{GetThemesResponse, PluginWindowContext};
use yaak_plugins::events::{GetThemesResponse, PluginContext};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::native_template_functions::{
decrypt_secure_template_function, encrypt_secure_template_function,
@@ -28,8 +28,8 @@ pub(crate) async fn cmd_decrypt_template<R: Runtime>(
template: &str,
) -> Result<String> {
let app_handle = window.app_handle();
let window_context = &PluginWindowContext::new(&window);
Ok(decrypt_secure_template_function(&app_handle, window_context, template)?)
let plugin_context = &PluginContext::new(&window);
Ok(decrypt_secure_template_function(&app_handle, plugin_context, template)?)
}
#[command]
@@ -38,8 +38,8 @@ pub(crate) async fn cmd_secure_template<R: Runtime>(
window: WebviewWindow<R>,
template: &str,
) -> Result<String> {
let window_context = &PluginWindowContext::new(&window);
Ok(encrypt_secure_template_function(&app_handle, window_context, template)?)
let plugin_context = &PluginContext::new(&window);
Ok(encrypt_secure_template_function(&app_handle, plugin_context, template)?)
}
#[command]

View File

@@ -16,6 +16,9 @@ pub enum Error {
#[error(transparent)]
CryptoError(#[from] yaak_crypto::error::Error),
#[error(transparent)]
HttpError(#[from] yaak_http::error::Error),
#[error(transparent)]
GitError(#[from] yaak_git::error::Error),

View File

@@ -6,7 +6,7 @@ use tauri::{Manager, Runtime, WebviewWindow};
use yaak_grpc::{KeyAndValueRef, MetadataMap};
use yaak_models::models::GrpcRequest;
use yaak_models::query_manager::QueryManagerExt;
use yaak_plugins::events::{CallHttpAuthenticationRequest, HttpHeader};
use yaak_plugins::events::{CallHttpAuthenticationRequest, HttpHeader, PluginContext};
use yaak_plugins::manager::PluginManager;
pub(crate) fn metadata_to_map(metadata: MetadataMap) -> BTreeMap<String, String> {
@@ -81,7 +81,12 @@ pub(crate) async fn build_metadata<R: Runtime>(
.collect(),
};
let plugin_result = plugin_manager
.call_http_authentication(&window, &authentication_type, plugin_req)
.call_http_authentication(
&window,
&authentication_type,
plugin_req,
&PluginContext::new(window),
)
.await?;
for header in plugin_result.set_headers.unwrap_or_default() {
metadata.insert(header.name, header.value);

View File

@@ -6,9 +6,9 @@ use http::header::{ACCEPT, USER_AGENT};
use http::{HeaderMap, HeaderName, HeaderValue};
use log::{debug, error, warn};
use mime_guess::Mime;
use reqwest::redirect::Policy;
use reqwest::{Method, NoProxy, Response};
use reqwest::{Proxy, Url, multipart};
use reqwest::{Method, Response};
use reqwest::{Url, multipart};
use reqwest_cookie_store::{CookieStore, CookieStoreMutex};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -21,6 +21,10 @@ use tokio::fs::{File, create_dir_all};
use tokio::io::AsyncWriteExt;
use tokio::sync::watch::Receiver;
use tokio::sync::{Mutex, oneshot};
use yaak_http::client::{
HttpConnectionOptions, HttpConnectionProxySetting, HttpConnectionProxySettingAuth,
};
use yaak_http::manager::HttpConnectionManager;
use yaak_models::models::{
Cookie, CookieJar, Environment, HttpRequest, HttpResponse, HttpResponseHeader,
HttpResponseState, ProxySetting, ProxySettingAuth,
@@ -28,12 +32,11 @@ use yaak_models::models::{
use yaak_models::query_manager::QueryManagerExt;
use yaak_models::util::UpdateSource;
use yaak_plugins::events::{
CallHttpAuthenticationRequest, HttpHeader, PluginWindowContext, RenderPurpose,
CallHttpAuthenticationRequest, HttpHeader, PluginContext, RenderPurpose,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_templates::{RenderErrorBehavior, RenderOptions};
use crate::dns::LocalhostResolver;
pub async fn send_http_request<R: Runtime>(
window: &WebviewWindow<R>,
@@ -42,9 +45,31 @@ pub async fn send_http_request<R: Runtime>(
environment: Option<Environment>,
cookie_jar: Option<CookieJar>,
cancelled_rx: &mut Receiver<bool>,
) -> Result<HttpResponse> {
send_http_request_with_context(
window,
unrendered_request,
og_response,
environment,
cookie_jar,
cancelled_rx,
&PluginContext::new(window),
)
.await
}
pub async fn send_http_request_with_context<R: Runtime>(
window: &WebviewWindow<R>,
unrendered_request: &HttpRequest,
og_response: &HttpResponse,
environment: Option<Environment>,
cookie_jar: Option<CookieJar>,
cancelled_rx: &mut Receiver<bool>,
plugin_context: &PluginContext,
) -> Result<HttpResponse> {
let app_handle = window.app_handle().clone();
let plugin_manager = app_handle.state::<PluginManager>();
let connection_manager = app_handle.state::<HttpConnectionManager>();
let settings = window.db().get_settings();
let workspace = window.db().get_workspace(&unrendered_request.workspace_id)?;
let environment_id = environment.map(|e| e.id);
@@ -72,11 +97,7 @@ pub async fn send_http_request<R: Runtime>(
}
};
let cb = PluginTemplateCallback::new(
window.app_handle(),
&PluginWindowContext::new(window),
RenderPurpose::Send,
);
let cb = PluginTemplateCallback::new(window.app_handle(), &plugin_context, RenderPurpose::Send);
let opt = RenderOptions {
error_behavior: RenderErrorBehavior::Throw,
@@ -102,65 +123,33 @@ pub async fn send_http_request<R: Runtime>(
}
debug!("Sending request to {} {url_string}", request.method);
let mut client_builder = reqwest::Client::builder()
.redirect(match workspace.setting_follow_redirects {
true => Policy::limited(10), // TODO: Handle redirects natively
false => Policy::none(),
})
.connection_verbose(true)
.gzip(true)
.brotli(true)
.deflate(true)
.dns_resolver(LocalhostResolver::new())
.referer(false)
.tls_info(true);
let tls_config = yaak_http::tls::get_config(workspace.setting_validate_certificates, true);
client_builder = client_builder.use_preconfigured_tls(tls_config);
match settings.proxy {
Some(ProxySetting::Disabled) => client_builder = client_builder.no_proxy(),
let proxy_setting = match settings.proxy {
None => HttpConnectionProxySetting::System,
Some(ProxySetting::Disabled) => HttpConnectionProxySetting::Disabled,
Some(ProxySetting::Enabled {
http,
https,
auth,
disabled,
bypass,
}) if !disabled => {
debug!("Using proxy http={http} https={https} bypass={bypass}");
if !http.is_empty() {
match Proxy::http(http) {
Ok(mut proxy) => {
if let Some(ProxySettingAuth { user, password }) = auth.clone() {
debug!("Using http proxy auth");
proxy = proxy.basic_auth(user.as_str(), password.as_str());
disabled,
}) => {
if disabled {
HttpConnectionProxySetting::System
} else {
HttpConnectionProxySetting::Enabled {
http,
https,
bypass,
auth: match auth {
None => None,
Some(ProxySettingAuth { user, password }) => {
Some(HttpConnectionProxySettingAuth { user, password })
}
proxy = proxy.no_proxy(NoProxy::from_string(&bypass));
client_builder = client_builder.proxy(proxy);
}
Err(e) => {
warn!("Failed to apply http proxy {e:?}");
}
};
}
if !https.is_empty() {
match Proxy::https(https) {
Ok(mut proxy) => {
if let Some(ProxySettingAuth { user, password }) = auth {
debug!("Using https proxy auth");
proxy = proxy.basic_auth(user.as_str(), password.as_str());
}
proxy = proxy.no_proxy(NoProxy::from_string(&bypass));
client_builder = client_builder.proxy(proxy);
}
Err(e) => {
warn!("Failed to apply https proxy {e:?}");
}
};
},
}
}
}
_ => {} // Nothing to do for this one, as it is the default
}
};
// Add cookie store if specified
let maybe_cookie_manager = match cookie_jar.clone() {
@@ -179,23 +168,33 @@ pub async fn send_http_request<R: Runtime>(
.map(|c| Ok(c))
.collect::<Vec<Result<_>>>();
let store = reqwest_cookie_store::CookieStore::from_cookies(cookies, true)?;
let cookie_store = reqwest_cookie_store::CookieStoreMutex::new(store);
let cookie_store = CookieStore::from_cookies(cookies, true)?;
let cookie_store = CookieStoreMutex::new(cookie_store);
let cookie_store = Arc::new(cookie_store);
client_builder = client_builder.cookie_provider(Arc::clone(&cookie_store));
Some((cookie_store, cj))
let cookie_provider = Arc::clone(&cookie_store);
Some((cookie_provider, cj))
}
None => None,
};
if workspace.setting_request_timeout > 0 {
client_builder = client_builder.timeout(Duration::from_millis(
workspace.setting_request_timeout.unsigned_abs() as u64,
));
}
let client = client_builder.build()?;
let client = connection_manager
.get_client(
&plugin_context.id,
&HttpConnectionOptions {
follow_redirects: workspace.setting_follow_redirects,
validate_certificates: workspace.setting_validate_certificates,
proxy: proxy_setting,
cookie_provider: maybe_cookie_manager.as_ref().map(|(p, _)| Arc::clone(&p)),
timeout: if workspace.setting_request_timeout > 0 {
Some(Duration::from_millis(
workspace.setting_request_timeout.unsigned_abs() as u64
))
} else {
None
},
},
)
.await?;
// Render query parameters
let mut query_params = Vec::new();
@@ -469,8 +468,9 @@ pub async fn send_http_request<R: Runtime>(
})
.collect(),
};
let auth_result =
plugin_manager.call_http_authentication(&window, &authentication_type, req).await;
let auth_result = plugin_manager
.call_http_authentication(&window, &authentication_type, req, plugin_context)
.await;
let plugin_result = match auth_result {
Ok(r) => r,
Err(e) => {

View File

@@ -23,7 +23,7 @@ use tauri::{Listener, Runtime};
use tauri::{Manager, WindowEvent};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_log::fern::colors::ColoredLevelConfig;
use tauri_plugin_log::{Builder, Target, TargetKind};
use tauri_plugin_log::{Builder, Target, TargetKind, log};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
use tokio::sync::Mutex;
use tokio::task::block_in_place;
@@ -44,7 +44,7 @@ use yaak_plugins::events::{
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse,
GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse,
GetTemplateFunctionSummaryResponse, InternalEvent, InternalEventPayload, JsonPrimitive,
PluginWindowContext, RenderPurpose, ShowToastRequest,
PluginContext, RenderPurpose, ShowToastRequest,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::plugin_meta::PluginMetadata;
@@ -54,7 +54,6 @@ use yaak_templates::format_json::format_json;
use yaak_templates::{RenderErrorBehavior, RenderOptions, Tokens, transform_args};
mod commands;
mod dns;
mod encoding;
mod error;
mod grpc;
@@ -104,7 +103,7 @@ async fn cmd_template_tokens_to_string<R: Runtime>(
) -> YaakResult<String> {
let cb = PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Preview,
);
let new_tokens = transform_args(tokens, &cb)?;
@@ -126,7 +125,7 @@ async fn cmd_render_template<R: Runtime>(
environment_chain,
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Preview,
),
&RenderOptions {
@@ -170,7 +169,7 @@ async fn cmd_grpc_reflect<R: Runtime>(
environment_chain,
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Send,
),
&RenderOptions {
@@ -219,7 +218,7 @@ async fn cmd_grpc_go<R: Runtime>(
environment_chain.clone(),
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Send,
),
&RenderOptions {
@@ -344,7 +343,7 @@ async fn cmd_grpc_go<R: Runtime>(
environment_chain,
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Send,
),
&RenderOptions {
@@ -416,7 +415,7 @@ async fn cmd_grpc_go<R: Runtime>(
environment_chain,
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Send,
),
&RenderOptions {
@@ -1162,7 +1161,7 @@ async fn cmd_install_plugin<R: Runtime>(
app_handle: AppHandle<R>,
window: WebviewWindow<R>,
) -> YaakResult<Plugin> {
plugin_manager.add_plugin_by_dir(&PluginWindowContext::new(&window), &directory).await?;
plugin_manager.add_plugin_by_dir(&PluginContext::new(&window), &directory).await?;
Ok(app_handle.db().upsert_plugin(
&Plugin {
@@ -1201,7 +1200,7 @@ async fn cmd_reload_plugins<R: Runtime>(
window: WebviewWindow<R>,
plugin_manager: State<'_, PluginManager>,
) -> YaakResult<()> {
plugin_manager.initialize_all_plugins(&app_handle, &PluginWindowContext::new(&window)).await?;
plugin_manager.initialize_all_plugins(&app_handle, &PluginContext::new(&window)).await?;
Ok(())
}
@@ -1351,6 +1350,7 @@ pub fn run() {
.plugin(yaak_crypto::init())
.plugin(yaak_fonts::init())
.plugin(yaak_git::init())
.plugin(yaak_http::init())
.plugin(yaak_ws::init())
.plugin(yaak_sync::init());
@@ -1621,13 +1621,13 @@ async fn call_frontend<R: Runtime>(
v.to_owned()
}
fn get_window_from_window_context<R: Runtime>(
fn get_window_from_plugin_context<R: Runtime>(
app_handle: &AppHandle<R>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
) -> Result<WebviewWindow<R>> {
let label = match window_context {
PluginWindowContext::Label { label, .. } => label,
PluginWindowContext::None => {
let label = match &plugin_context.label {
Some(label) => label,
None => {
return app_handle
.webview_windows()
.iter()
@@ -1643,7 +1643,7 @@ fn get_window_from_window_context<R: Runtime>(
.find_map(|(_, w)| if w.label() == label { Some(w.to_owned()) } else { None });
if window.is_none() {
error!("Failed to find window by {window_context:?}");
error!("Failed to find window by {plugin_context:?}");
}
Ok(window.ok_or(GenericError(format!("Failed to find window for {}", label)))?)

View File

@@ -1,14 +1,14 @@
use crate::error::Result;
use crate::http_request::send_http_request;
use crate::http_request::send_http_request_with_context;
use crate::render::{render_grpc_request, render_http_request, render_json_value};
use crate::window::{CreateWindowConfig, create_window};
use crate::{
call_frontend, cookie_jar_from_window, environment_from_window, get_window_from_window_context,
call_frontend, cookie_jar_from_window, environment_from_window, get_window_from_plugin_context,
workspace_from_window,
};
use chrono::Utc;
use cookie::Cookie;
use log::error;
use log::{debug, error};
use tauri::{AppHandle, Emitter, Manager, Runtime};
use tauri_plugin_clipboard_manager::ClipboardExt;
use yaak_common::window::WorkspaceWindowTrait;
@@ -19,7 +19,7 @@ use yaak_models::util::UpdateSource;
use yaak_plugins::events::{
Color, DeleteKeyValueResponse, EmptyPayload, ErrorResponse, FindHttpResponsesResponse,
GetCookieValueResponse, GetHttpRequestByIdResponse, GetKeyValueResponse, Icon, InternalEvent,
InternalEventPayload, ListCookieNamesResponse, PluginWindowContext, RenderGrpcRequestResponse,
InternalEventPayload, ListCookieNamesResponse, RenderGrpcRequestResponse,
RenderHttpRequestResponse, SendHttpRequestResponse, SetKeyValueResponse, ShowToastRequest,
TemplateRenderResponse, WindowNavigateEvent,
};
@@ -33,23 +33,21 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
plugin_handle: &PluginHandle,
) -> Result<Option<InternalEventPayload>> {
// debug!("Got event to app {event:?}");
let window_context = event.window_context.to_owned();
let plugin_context = event.context.to_owned();
match event.clone().payload {
InternalEventPayload::CopyTextRequest(req) => {
app_handle.clipboard().write_text(req.text.as_str())?;
Ok(Some(InternalEventPayload::CopyTextResponse(EmptyPayload {})))
}
InternalEventPayload::ShowToastRequest(req) => {
match window_context {
PluginWindowContext::Label { label, .. } => {
app_handle.emit_to(label, "show_toast", req)?
}
_ => app_handle.emit("show_toast", req)?,
match plugin_context.label {
Some(label) => app_handle.emit_to(label, "show_toast", req)?,
None => app_handle.emit("show_toast", req)?,
};
Ok(Some(InternalEventPayload::ShowToastResponse(EmptyPayload {})))
}
InternalEventPayload::PromptTextRequest(_) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
Ok(call_frontend(&window, event).await)
}
InternalEventPayload::FindHttpResponsesRequest(req) => {
@@ -68,7 +66,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
})))
}
InternalEventPayload::RenderGrpcRequestRequest(req) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
let workspace =
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
@@ -78,7 +76,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
req.grpc_request.folder_id.as_deref(),
environment_id.as_deref(),
)?;
let cb = PluginTemplateCallback::new(app_handle, &window_context, req.purpose);
let cb = PluginTemplateCallback::new(app_handle, &plugin_context, req.purpose);
let opt = RenderOptions {
error_behavior: RenderErrorBehavior::Throw,
};
@@ -89,7 +87,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
})))
}
InternalEventPayload::RenderHttpRequestRequest(req) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
let workspace =
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
@@ -99,7 +97,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
req.http_request.folder_id.as_deref(),
environment_id.as_deref(),
)?;
let cb = PluginTemplateCallback::new(app_handle, &window_context, req.purpose);
let cb = PluginTemplateCallback::new(app_handle, &plugin_context, req.purpose);
let opt = &RenderOptions {
error_behavior: RenderErrorBehavior::Throw,
};
@@ -110,7 +108,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
})))
}
InternalEventPayload::TemplateRenderRequest(req) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
let workspace =
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
@@ -130,7 +128,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
folder_id.as_deref(),
environment_id.as_deref(),
)?;
let cb = PluginTemplateCallback::new(app_handle, &window_context, req.purpose);
let cb = PluginTemplateCallback::new(app_handle, &plugin_context, req.purpose);
let opt = RenderOptions {
error_behavior: RenderErrorBehavior::Throw,
};
@@ -140,7 +138,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
InternalEventPayload::ErrorResponse(resp) => {
error!("Plugin error: {}: {:?}", resp.error, resp);
let toast_event = plugin_handle.build_event_to_send(
&window_context,
&plugin_context,
&InternalEventPayload::ShowToastRequest(ShowToastRequest {
message: format!(
"Plugin error from {}: {}",
@@ -172,7 +170,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
if !req.silent {
let info = plugin_handle.info();
let toast_event = plugin_handle.build_event_to_send(
&window_context,
&plugin_context,
&InternalEventPayload::ShowToastRequest(ShowToastRequest {
message: format!("Reloaded plugin {}@{}", info.name, info.version),
icon: Some(Icon::Info),
@@ -187,7 +185,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
}
}
InternalEventPayload::SendHttpRequestRequest(req) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
let mut http_request = req.http_request;
let workspace =
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
@@ -211,13 +209,14 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
)?
};
let http_response = send_http_request(
let http_response = send_http_request_with_context(
&window,
&http_request,
&http_response,
environment,
cookie_jar,
&mut tokio::sync::watch::channel(false).1, // No-op cancel channel
&plugin_context,
)
.await?;
@@ -240,7 +239,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
};
if let Err(e) = create_window(app_handle, win_config) {
let error_event = plugin_handle.build_event_to_send(
&window_context,
&plugin_context,
&InternalEventPayload::ErrorResponse(ErrorResponse {
error: format!("Failed to create window: {:?}", e),
}),
@@ -253,12 +252,12 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
{
let event_id = event.id.clone();
let plugin_handle = plugin_handle.clone();
let window_context = window_context.clone();
let plugin_context = plugin_context.clone();
tauri::async_runtime::spawn(async move {
while let Some(url) = navigation_rx.recv().await {
let url = url.to_string();
let event_to_send = plugin_handle.build_event_to_send(
&window_context, // NOTE: Sending existing context on purpose here
&plugin_context, // NOTE: Sending existing context on purpose here
&InternalEventPayload::WindowNavigateEvent(WindowNavigateEvent { url }),
Some(event_id.clone()),
);
@@ -270,11 +269,11 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
{
let event_id = event.id.clone();
let plugin_handle = plugin_handle.clone();
let window_context = window_context.clone();
let plugin_context = plugin_context.clone();
tauri::async_runtime::spawn(async move {
while let Some(_) = close_rx.recv().await {
let event_to_send = plugin_handle.build_event_to_send(
&window_context,
&plugin_context,
&InternalEventPayload::WindowCloseEvent,
Some(event_id.clone()),
);
@@ -309,7 +308,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
})))
}
InternalEventPayload::ListCookieNamesRequest(_req) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
let names = match cookie_jar_from_window(&window) {
None => Vec::new(),
Some(j) => j
@@ -323,7 +322,7 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
})))
}
InternalEventPayload::GetCookieValueRequest(req) => {
let window = get_window_from_window_context(app_handle, &window_context)?;
let window = get_window_from_plugin_context(app_handle, &plugin_context)?;
let value = match cookie_jar_from_window(&window) {
None => None,
Some(j) => j.cookies.into_iter().find_map(|c| match Cookie::parse(c.raw_cookie) {

View File

@@ -1,11 +1,11 @@
use serde_json::Value;
use std::collections::BTreeMap;
use yaak_http::apply_path_placeholders;
use yaak_http::path_placeholders::apply_path_placeholders;
use yaak_models::models::{
Environment, GrpcRequest, HttpRequest, HttpRequestHeader, HttpUrlParameter,
};
use yaak_models::render::make_vars_hashmap;
use yaak_templates::{RenderOptions, TemplateCallback, parse_and_render, render_json_value_raw};
use yaak_templates::{parse_and_render, render_json_value_raw, RenderOptions, TemplateCallback};
pub async fn render_template<T: TemplateCallback>(
template: &str,

View File

@@ -10,7 +10,7 @@ base32 = "0.5.1" # For encoding human-readable key
base64 = "0.22.1" # For encoding in the database
chacha20poly1305 = "0.10.1"
keyring = { workspace = true, features = ["apple-native", "windows-native", "sync-secret-service"] }
log = "0.4.26"
log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
tauri = { workspace = true }
thiserror = { workspace = true }

View File

@@ -8,7 +8,7 @@ publish = false
[dependencies]
chrono = { workspace = true, features = ["serde"] }
git2 = { version = "0.20.0", features = ["vendored-libgit2", "vendored-openssl"] }
log = "0.4.22"
log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml = "0.9.34"

View File

@@ -10,7 +10,7 @@ async-recursion = "1.1.1"
dunce = "1.0.4"
hyper-rustls = { version = "0.27.7", default-features = false, features = ["http2"] }
hyper-util = { version = "0.1.13", default-features = false, features = ["client-legacy"] }
log = "0.4.20"
log = { workspace = true }
md5 = "0.7.0"
prost = "0.13.4"
prost-reflect = { version = "0.14.4", default-features = false, features = ["serde", "derive"] }

View File

@@ -10,3 +10,12 @@ regex = "1.11.1"
rustls = { workspace = true, default-features = false, features = ["ring"] }
rustls-platform-verifier = { workspace = true }
urlencoding = "2.1.3"
tauri = { workspace = true }
tokio = { workspace = true }
reqwest = { workspace = true, features = ["multipart", "cookies", "gzip", "brotli", "deflate", "json", "rustls-tls-manual-roots-no-provider", "socks", "http2"] }
reqwest_cookie_store = { workspace = true }
thiserror = { workspace = true }
serde = { workspace = true, features = ["derive"] }
hyper-util = { version = "0.1.17", default-features = false, features = ["client-legacy"] }
tower-service = "0.3.3"
log = { workspace = true }

View File

@@ -0,0 +1,133 @@
use crate::dns::LocalhostResolver;
use crate::error::Result;
use crate::tls;
use log::{debug, warn};
use reqwest::redirect::Policy;
use reqwest::{Client, Proxy};
use reqwest_cookie_store::CookieStoreMutex;
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone)]
pub struct HttpConnectionProxySettingAuth {
pub user: String,
pub password: String,
}
#[derive(Clone)]
pub enum HttpConnectionProxySetting {
Disabled,
System,
Enabled {
http: String,
https: String,
auth: Option<HttpConnectionProxySettingAuth>,
bypass: String,
},
}
#[derive(Clone)]
pub struct HttpConnectionOptions {
pub follow_redirects: bool,
pub validate_certificates: bool,
pub proxy: HttpConnectionProxySetting,
pub cookie_provider: Option<Arc<CookieStoreMutex>>,
pub timeout: Option<Duration>,
}
impl HttpConnectionOptions {
pub(crate) fn build_client(&self) -> Result<Client> {
let mut client = Client::builder()
.connection_verbose(true)
.gzip(true)
.brotli(true)
.deflate(true)
.referer(false)
.tls_info(true);
// Configure TLS
client = client.use_preconfigured_tls(tls::get_config(self.validate_certificates, true));
// Configure DNS resolver
client = client.dns_resolver(LocalhostResolver::new());
// Configure redirects
client = client.redirect(match self.follow_redirects {
true => Policy::limited(10), // TODO: Handle redirects natively
false => Policy::none(),
});
// Configure cookie provider
if let Some(p) = &self.cookie_provider {
client = client.cookie_provider(Arc::clone(&p));
}
// Configure proxy
match self.proxy.clone() {
HttpConnectionProxySetting::System => { /* Default */ }
HttpConnectionProxySetting::Disabled => {
client = client.no_proxy();
}
HttpConnectionProxySetting::Enabled {
http,
https,
auth,
bypass,
} => {
for p in build_enabled_proxy(http, https, auth, bypass) {
client = client.proxy(p)
}
}
}
// Configure timeout
if let Some(d) = self.timeout {
client = client.timeout(d);
}
Ok(client.build()?)
}
}
fn build_enabled_proxy(
http: String,
https: String,
auth: Option<HttpConnectionProxySettingAuth>,
bypass: String,
) -> Vec<Proxy> {
debug!("Using proxy http={http} https={https} bypass={bypass}");
let mut proxies = Vec::new();
if !http.is_empty() {
match Proxy::http(http) {
Ok(mut proxy) => {
if let Some(HttpConnectionProxySettingAuth { user, password }) = auth.clone() {
debug!("Using http proxy auth");
proxy = proxy.basic_auth(user.as_str(), password.as_str());
}
proxies.push(proxy.no_proxy(reqwest::NoProxy::from_string(&bypass)));
}
Err(e) => {
warn!("Failed to apply http proxy {e:?}");
}
};
}
if !https.is_empty() {
match Proxy::https(https) {
Ok(mut proxy) => {
if let Some(HttpConnectionProxySettingAuth { user, password }) = auth {
debug!("Using https proxy auth");
proxy = proxy.basic_auth(user.as_str(), password.as_str());
}
proxies.push(proxy.no_proxy(reqwest::NoProxy::from_string(&bypass)));
}
Err(e) => {
warn!("Failed to apply https proxy {e:?}");
}
};
}
proxies
}

View File

@@ -8,7 +8,7 @@ use std::sync::Arc;
use tower_service::Service;
#[derive(Clone)]
pub(crate) struct LocalhostResolver {
pub struct LocalhostResolver {
fallback: HyperGaiResolver,
}

View File

@@ -0,0 +1,19 @@
use serde::{Serialize, Serializer};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
Client(#[from] reqwest::Error),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
pub type Result<T> = std::result::Result<T, Error>;

View File

@@ -1,185 +1,20 @@
use crate::manager::HttpConnectionManager;
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{Manager, Runtime};
pub mod tls;
pub mod path_placeholders;
pub mod error;
pub mod manager;
pub mod dns;
pub mod client;
use yaak_models::models::HttpUrlParameter;
pub fn apply_path_placeholders(
url: &str,
parameters: Vec<HttpUrlParameter>,
) -> (String, Vec<HttpUrlParameter>) {
let mut new_parameters = Vec::new();
let mut url = url.to_string();
for p in parameters {
if !p.enabled || p.name.is_empty() {
continue;
}
// Replace path parameters with values from URL parameters
let old_url_string = url.clone();
url = replace_path_placeholder(&p, url.as_str());
// Remove as param if it modified the URL
if old_url_string == *url {
new_parameters.push(p);
}
}
(url, new_parameters)
}
fn replace_path_placeholder(p: &HttpUrlParameter, url: &str) -> String {
if !p.enabled {
return url.to_string();
}
if !p.name.starts_with(":") {
return url.to_string();
}
let re = regex::Regex::new(format!("(/){}([/?#]|$)", p.name).as_str()).unwrap();
let result = re
.replace_all(url, |cap: &regex::Captures| {
format!(
"{}{}{}",
cap[1].to_string(),
urlencoding::encode(p.value.as_str()),
cap[2].to_string()
)
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("yaak-http")
.setup(|app, _api| {
let manager = HttpConnectionManager::new();
app.manage(manager);
Ok(())
})
.into_owned();
result
}
#[cfg(test)]
mod placeholder_tests {
use crate::{apply_path_placeholders, replace_path_placeholder};
use yaak_models::models::{HttpRequest, HttpUrlParameter};
#[test]
fn placeholder_middle() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo/bar"),
"https://example.com/xxx/bar",
);
}
#[test]
fn placeholder_end() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo"),
"https://example.com/xxx",
);
}
#[test]
fn placeholder_query() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo?:foo"),
"https://example.com/xxx?:foo",
);
}
#[test]
fn placeholder_missing() {
let p = HttpUrlParameter {
enabled: true,
name: "".to_string(),
value: "".to_string(),
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:missing"),
"https://example.com/:missing",
);
}
#[test]
fn placeholder_disabled() {
let p = HttpUrlParameter {
enabled: false,
name: ":foo".to_string(),
value: "xxx".to_string(),
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo"),
"https://example.com/:foo",
);
}
#[test]
fn placeholder_prefix() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foooo"),
"https://example.com/:foooo",
);
}
#[test]
fn placeholder_encode() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "Hello World".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo"),
"https://example.com/Hello%20World",
);
}
#[test]
fn apply_placeholder() {
let req = HttpRequest {
url: "example.com/:a/bar".to_string(),
url_parameters: vec![
HttpUrlParameter {
name: "b".to_string(),
value: "bbb".to_string(),
enabled: true,
id: None,
},
HttpUrlParameter {
name: ":a".to_string(),
value: "aaa".to_string(),
enabled: true,
id: None,
},
],
..Default::default()
};
let (url, url_parameters) = apply_path_placeholders(&req.url, req.url_parameters);
// Pattern match back to access it
assert_eq!(url, "example.com/aaa/bar");
assert_eq!(url_parameters.len(), 1);
assert_eq!(url_parameters[0].name, "b");
assert_eq!(url_parameters[0].value, "bbb");
}
.build()
}

View File

@@ -0,0 +1,40 @@
use crate::client::HttpConnectionOptions;
use crate::error::Result;
use log::info;
use reqwest::Client;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
pub struct HttpConnectionManager {
connections: Arc<RwLock<BTreeMap<String, (Client, Instant)>>>,
ttl: Duration,
}
impl HttpConnectionManager {
pub fn new() -> Self {
Self {
connections: Arc::new(RwLock::new(BTreeMap::new())),
ttl: Duration::from_mins(10),
}
}
pub async fn get_client(&self, id: &str, opt: &HttpConnectionOptions) -> Result<Client> {
let mut connections = self.connections.write().await;
// Clean old connections
connections.retain(|_, (_, last_used)| last_used.elapsed() <= self.ttl);
if let Some((c, last_used)) = connections.get_mut(id) {
info!("Re-using HTTP client {id}");
*last_used = Instant::now();
return Ok(c.clone());
}
info!("Building new HTTP client {id}");
let c = opt.build_client()?;
connections.insert(id.into(), (c.clone(), Instant::now()));
Ok(c)
}
}

View File

@@ -0,0 +1,183 @@
use yaak_models::models::HttpUrlParameter;
pub fn apply_path_placeholders(
url: &str,
parameters: Vec<HttpUrlParameter>,
) -> (String, Vec<HttpUrlParameter>) {
let mut new_parameters = Vec::new();
let mut url = url.to_string();
for p in parameters {
if !p.enabled || p.name.is_empty() {
continue;
}
// Replace path parameters with values from URL parameters
let old_url_string = url.clone();
url = replace_path_placeholder(&p, url.as_str());
// Remove as param if it modified the URL
if old_url_string == *url {
new_parameters.push(p);
}
}
(url, new_parameters)
}
fn replace_path_placeholder(p: &HttpUrlParameter, url: &str) -> String {
if !p.enabled {
return url.to_string();
}
if !p.name.starts_with(":") {
return url.to_string();
}
let re = regex::Regex::new(format!("(/){}([/?#]|$)", p.name).as_str()).unwrap();
let result = re
.replace_all(url, |cap: &regex::Captures| {
format!(
"{}{}{}",
cap[1].to_string(),
urlencoding::encode(p.value.as_str()),
cap[2].to_string()
)
})
.into_owned();
result
}
#[cfg(test)]
mod placeholder_tests {
use crate::path_placeholders::{apply_path_placeholders, replace_path_placeholder};
use yaak_models::models::{HttpRequest, HttpUrlParameter};
#[test]
fn placeholder_middle() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo/bar"),
"https://example.com/xxx/bar",
);
}
#[test]
fn placeholder_end() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo"),
"https://example.com/xxx",
);
}
#[test]
fn placeholder_query() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo?:foo"),
"https://example.com/xxx?:foo",
);
}
#[test]
fn placeholder_missing() {
let p = HttpUrlParameter {
enabled: true,
name: "".to_string(),
value: "".to_string(),
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:missing"),
"https://example.com/:missing",
);
}
#[test]
fn placeholder_disabled() {
let p = HttpUrlParameter {
enabled: false,
name: ":foo".to_string(),
value: "xxx".to_string(),
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo"),
"https://example.com/:foo",
);
}
#[test]
fn placeholder_prefix() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "xxx".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foooo"),
"https://example.com/:foooo",
);
}
#[test]
fn placeholder_encode() {
let p = HttpUrlParameter {
name: ":foo".into(),
value: "Hello World".into(),
enabled: true,
id: None,
};
assert_eq!(
replace_path_placeholder(&p, "https://example.com/:foo"),
"https://example.com/Hello%20World",
);
}
#[test]
fn apply_placeholder() {
let req = HttpRequest {
url: "example.com/:a/bar".to_string(),
url_parameters: vec![
HttpUrlParameter {
name: "b".to_string(),
value: "bbb".to_string(),
enabled: true,
id: None,
},
HttpUrlParameter {
name: ":a".to_string(),
value: "aaa".to_string(),
enabled: true,
id: None,
},
],
..Default::default()
};
let (url, url_parameters) = apply_path_placeholders(&req.url, req.url_parameters);
// Pattern match back to access it
assert_eq!(url, "example.com/aaa/bar");
assert_eq!(url_parameters.len(), 1);
assert_eq!(url_parameters[0].name, "b");
assert_eq!(url_parameters[0].value, "bbb");
}
}

View File

@@ -7,7 +7,7 @@ publish = false
[dependencies]
chrono = "0.4.38"
log = "0.4.26"
log = { workspace = true }
reqwest = { workspace = true, features = ["json"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }

View File

@@ -1,7 +1,7 @@
use crate::error::Error::{ClientError, ServerError};
use crate::error::Result;
use chrono::{NaiveDateTime, Utc};
use log::{debug, info, warn};
use log::{info, warn};
use serde::{Deserialize, Serialize};
use std::ops::Add;
use std::time::Duration;

View File

@@ -10,7 +10,7 @@ tauri-plugin = { workspace = true, features = ["build"] }
[target.'cfg(target_os = "macos")'.dependencies]
cocoa = "0.26.0"
log = "0.4.27"
log = { workspace = true }
objc = "0.2.7"
rand = "0.9.0"
csscolorparser = "0.7.2"

View File

@@ -9,7 +9,7 @@ publish = false
chrono = { version = "0.4.38", features = ["serde"] }
hex = { workspace = true }
include_dir = "0.7"
log = "0.4.22"
log = { workspace = true }
nanoid = "0.4.0"
r2d2 = "0.8.10"
r2d2_sqlite = { version = "0.25.0" }

View File

@@ -12,7 +12,7 @@ dunce = "1.0.4"
futures-util = "0.3.30"
hex = { workspace = true }
keyring = { workspace = true, features = ["apple-native", "windows-native", "sync-secret-service"] }
log = "0.4.21"
log = { workspace = true }
md5 = "0.7.0"
path-slash = "0.2.1"
rand = "0.9.0"

View File

@@ -387,7 +387,7 @@ export type ImportResources = { workspaces: Array<Workspace>, environments: Arra
export type ImportResponse = { resources: ImportResources, };
export type InternalEvent = { id: string, pluginRefId: string, pluginName: string, replyId: string | null, windowContext: PluginWindowContext, payload: InternalEventPayload, };
export type InternalEvent = { id: string, pluginRefId: string, pluginName: string, replyId: string | null, context: PluginContext, payload: InternalEventPayload, };
export type InternalEventPayload = { "type": "boot_request" } & BootRequest | { "type": "boot_response" } | { "type": "reload_response" } & ReloadResponse | { "type": "terminate_request" } | { "type": "terminate_response" } | { "type": "import_request" } & ImportRequest | { "type": "import_response" } & ImportResponse | { "type": "filter_request" } & FilterRequest | { "type": "filter_response" } & FilterResponse | { "type": "export_http_request_request" } & ExportHttpRequestRequest | { "type": "export_http_request_response" } & ExportHttpRequestResponse | { "type": "send_http_request_request" } & SendHttpRequestRequest | { "type": "send_http_request_response" } & SendHttpRequestResponse | { "type": "list_cookie_names_request" } & ListCookieNamesRequest | { "type": "list_cookie_names_response" } & ListCookieNamesResponse | { "type": "get_cookie_value_request" } & GetCookieValueRequest | { "type": "get_cookie_value_response" } & GetCookieValueResponse | { "type": "get_http_request_actions_request" } & EmptyPayload | { "type": "get_http_request_actions_response" } & GetHttpRequestActionsResponse | { "type": "call_http_request_action_request" } & CallHttpRequestActionRequest | { "type": "get_grpc_request_actions_request" } & EmptyPayload | { "type": "get_grpc_request_actions_response" } & GetGrpcRequestActionsResponse | { "type": "call_grpc_request_action_request" } & CallGrpcRequestActionRequest | { "type": "get_template_function_summary_request" } & EmptyPayload | { "type": "get_template_function_summary_response" } & GetTemplateFunctionSummaryResponse | { "type": "get_template_function_config_request" } & GetTemplateFunctionConfigRequest | { "type": "get_template_function_config_response" } & GetTemplateFunctionConfigResponse | { "type": "call_template_function_request" } & CallTemplateFunctionRequest | { "type": "call_template_function_response" } & CallTemplateFunctionResponse | { "type": "get_http_authentication_summary_request" } & EmptyPayload | { "type": "get_http_authentication_summary_response" } & GetHttpAuthenticationSummaryResponse | { "type": "get_http_authentication_config_request" } & GetHttpAuthenticationConfigRequest | { "type": "get_http_authentication_config_response" } & GetHttpAuthenticationConfigResponse | { "type": "call_http_authentication_request" } & CallHttpAuthenticationRequest | { "type": "call_http_authentication_response" } & CallHttpAuthenticationResponse | { "type": "call_http_authentication_action_request" } & CallHttpAuthenticationActionRequest | { "type": "call_http_authentication_action_response" } & EmptyPayload | { "type": "copy_text_request" } & CopyTextRequest | { "type": "copy_text_response" } & EmptyPayload | { "type": "render_http_request_request" } & RenderHttpRequestRequest | { "type": "render_http_request_response" } & RenderHttpRequestResponse | { "type": "render_grpc_request_request" } & RenderGrpcRequestRequest | { "type": "render_grpc_request_response" } & RenderGrpcRequestResponse | { "type": "template_render_request" } & TemplateRenderRequest | { "type": "template_render_response" } & TemplateRenderResponse | { "type": "get_key_value_request" } & GetKeyValueRequest | { "type": "get_key_value_response" } & GetKeyValueResponse | { "type": "set_key_value_request" } & SetKeyValueRequest | { "type": "set_key_value_response" } & SetKeyValueResponse | { "type": "delete_key_value_request" } & DeleteKeyValueRequest | { "type": "delete_key_value_response" } & DeleteKeyValueResponse | { "type": "open_window_request" } & OpenWindowRequest | { "type": "window_navigate_event" } & WindowNavigateEvent | { "type": "window_close_event" } | { "type": "close_window_request" } & CloseWindowRequest | { "type": "show_toast_request" } & ShowToastRequest | { "type": "show_toast_response" } & EmptyPayload | { "type": "prompt_text_request" } & PromptTextRequest | { "type": "prompt_text_response" } & PromptTextResponse | { "type": "get_http_request_by_id_request" } & GetHttpRequestByIdRequest | { "type": "get_http_request_by_id_response" } & GetHttpRequestByIdResponse | { "type": "find_http_responses_request" } & FindHttpResponsesRequest | { "type": "find_http_responses_response" } & FindHttpResponsesResponse | { "type": "get_themes_request" } & GetThemesRequest | { "type": "get_themes_response" } & GetThemesResponse | { "type": "empty_response" } & EmptyPayload | { "type": "error_response" } & ErrorResponse;
@@ -403,7 +403,7 @@ export type OpenWindowRequest = { url: string,
*/
label: string, title?: string, size?: WindowSize, dataDirKey?: string, };
export type PluginWindowContext = { "type": "none" } | { "type": "label", label: string, workspace_id: string | null, };
export type PluginContext = { id: string, label: string | null, workspaceId: string | null, };
export type PromptTextRequest = { id: string, title: string, label: string, description?: string, defaultValue?: string, placeholder?: string,
/**

View File

@@ -6,6 +6,7 @@ use yaak_common::window::WorkspaceWindowTrait;
use yaak_models::models::{
Environment, Folder, GrpcRequest, HttpRequest, HttpResponse, WebsocketRequest, Workspace,
};
use yaak_models::util::generate_prefixed_id;
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
@@ -15,7 +16,7 @@ pub struct InternalEvent {
pub plugin_ref_id: String,
pub plugin_name: String,
pub reply_id: Option<String>,
pub window_context: PluginWindowContext,
pub context: PluginContext,
pub payload: InternalEventPayload,
}
@@ -29,32 +30,32 @@ pub(crate) struct InternalEventRawPayload {
pub plugin_ref_id: String,
pub plugin_name: String,
pub reply_id: Option<String>,
pub window_context: PluginWindowContext,
pub context: PluginContext,
pub payload: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case", tag = "type")]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_events.ts")]
pub enum PluginWindowContext {
None,
Label {
label: String,
workspace_id: Option<String>,
},
pub struct PluginContext {
pub id: String,
pub label: Option<String>,
pub workspace_id: Option<String>,
}
impl PluginWindowContext {
pub fn new<R: Runtime>(window: &WebviewWindow<R>) -> Self {
Self::Label {
label: window.label().to_string(),
workspace_id: window.workspace_id(),
impl PluginContext {
pub fn new_empty() -> Self {
Self {
id: "default".to_string(),
label: None,
workspace_id: None,
}
}
pub fn new_no_workspace<R: Runtime>(window: &WebviewWindow<R>) -> Self {
Self::Label {
label: window.label().to_string(),
workspace_id: None,
pub fn new<R: Runtime>(window: &WebviewWindow<R>) -> Self {
Self {
label: Some(window.label().to_string()),
workspace_id: window.workspace_id(),
id: generate_prefixed_id("pctx"),
}
}
}

View File

@@ -2,7 +2,7 @@ use crate::api::{PluginVersion, download_plugin_archive, get_plugin};
use crate::checksum::compute_checksum;
use crate::error::Error::PluginErr;
use crate::error::Result;
use crate::events::PluginWindowContext;
use crate::events::PluginContext;
use crate::manager::PluginManager;
use chrono::Utc;
use log::info;
@@ -19,7 +19,7 @@ pub async fn delete_and_uninstall<R: Runtime>(
) -> Result<Plugin> {
let plugin_manager = window.state::<PluginManager>();
let plugin = window.db().delete_plugin_by_id(plugin_id, &UpdateSource::from_window(&window))?;
plugin_manager.uninstall(&PluginWindowContext::new(&window), plugin.directory.as_str()).await?;
plugin_manager.uninstall(&PluginContext::new(&window), plugin.directory.as_str()).await?;
Ok(plugin)
}
@@ -55,7 +55,7 @@ pub async fn download_and_install<R: Runtime>(
zip_extract::extract(Cursor::new(&bytes), &plugin_dir, true)?;
info!("Extracted plugin {} to {}", plugin_version.id, plugin_dir_str);
plugin_manager.add_plugin_by_dir(&PluginWindowContext::new(&window), &plugin_dir_str).await?;
plugin_manager.add_plugin_by_dir(&PluginContext::new(&window), &plugin_dir_str).await?;
window.db().upsert_plugin(
&Plugin {

View File

@@ -12,7 +12,7 @@ use crate::events::{
GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse,
GetTemplateFunctionConfigRequest, GetTemplateFunctionConfigResponse,
GetTemplateFunctionSummaryResponse, GetThemesRequest, GetThemesResponse, ImportRequest,
ImportResponse, InternalEvent, InternalEventPayload, JsonPrimitive, PluginWindowContext,
ImportResponse, InternalEvent, InternalEventPayload, JsonPrimitive, PluginContext,
RenderPurpose,
};
use crate::native_template_functions::{template_function_keyring, template_function_secure};
@@ -132,7 +132,7 @@ impl PluginManager {
Ok(_) => {
info!("Plugin runtime client connected!");
plugin_manager
.initialize_all_plugins(&app_handle, &PluginWindowContext::None)
.initialize_all_plugins(&app_handle, &PluginContext::new_empty())
.await
.expect("Failed to reload plugins");
}
@@ -195,19 +195,19 @@ impl PluginManager {
[bundled_plugin_dirs, installed_plugin_dirs].concat()
}
pub async fn uninstall(&self, window_context: &PluginWindowContext, dir: &str) -> Result<()> {
pub async fn uninstall(&self, plugin_context: &PluginContext, dir: &str) -> Result<()> {
let plugin = self.get_plugin_by_dir(dir).await.ok_or(PluginNotFoundErr(dir.to_string()))?;
self.remove_plugin(window_context, &plugin).await
self.remove_plugin(plugin_context, &plugin).await
}
async fn remove_plugin(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
plugin: &PluginHandle,
) -> Result<()> {
// Terminate the plugin
self.send_to_plugin_and_wait(
window_context,
plugin_context,
plugin,
&InternalEventPayload::TerminateRequest,
)
@@ -223,11 +223,7 @@ impl PluginManager {
Ok(())
}
pub async fn add_plugin_by_dir(
&self,
window_context: &PluginWindowContext,
dir: &str,
) -> Result<()> {
pub async fn add_plugin_by_dir(&self, plugin_context: &PluginContext, dir: &str) -> Result<()> {
info!("Adding plugin by dir {dir}");
let maybe_tx = self.ws_service.app_to_plugin_events_tx.lock().await;
@@ -244,7 +240,7 @@ impl PluginManager {
let event = timeout(
Duration::from_secs(5),
self.send_to_plugin_and_wait(
window_context,
plugin_context,
&plugin_handle,
&InternalEventPayload::BootRequest(BootRequest {
dir: dir.to_string(),
@@ -268,19 +264,19 @@ impl PluginManager {
pub async fn initialize_all_plugins<R: Runtime>(
&self,
app_handle: &AppHandle<R>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
) -> Result<()> {
let start = Instant::now();
let candidates = self.list_plugin_dirs(app_handle).await;
for candidate in candidates.clone() {
// First remove the plugin if it exists
if let Some(plugin) = self.get_plugin_by_dir(candidate.dir.as_str()).await {
if let Err(e) = self.remove_plugin(window_context, &plugin).await {
if let Err(e) = self.remove_plugin(plugin_context, &plugin).await {
error!("Failed to remove plugin {} {e:?}", candidate.dir);
continue;
}
}
if let Err(e) = self.add_plugin_by_dir(window_context, candidate.dir.as_str()).await {
if let Err(e) = self.add_plugin_by_dir(plugin_context, candidate.dir.as_str()).await {
warn!("Failed to add plugin {} {e:?}", candidate.dir);
}
}
@@ -320,13 +316,13 @@ impl PluginManager {
source_event: &InternalEvent,
payload: &InternalEventPayload,
) -> Result<()> {
let window_context = source_event.to_owned().window_context;
let plugin_context = source_event.to_owned().context;
let reply_id = Some(source_event.to_owned().id);
let plugin = self
.get_plugin_by_ref_id(source_event.plugin_ref_id.as_str())
.await
.ok_or(PluginNotFoundErr(source_event.plugin_ref_id.to_string()))?;
let event = plugin.build_event_to_send_raw(&window_context, &payload, reply_id);
let event = plugin.build_event_to_send_raw(&plugin_context, &payload, reply_id);
plugin.send(&event).await
}
@@ -350,27 +346,27 @@ impl PluginManager {
async fn send_to_plugin_and_wait(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
plugin: &PluginHandle,
payload: &InternalEventPayload,
) -> Result<InternalEvent> {
let events =
self.send_to_plugins_and_wait(window_context, payload, vec![plugin.to_owned()]).await?;
self.send_to_plugins_and_wait(plugin_context, payload, vec![plugin.to_owned()]).await?;
Ok(events.first().unwrap().to_owned())
}
async fn send_and_wait(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
payload: &InternalEventPayload,
) -> Result<Vec<InternalEvent>> {
let plugins = { self.plugins.lock().await.clone() };
self.send_to_plugins_and_wait(window_context, payload, plugins).await
self.send_to_plugins_and_wait(plugin_context, payload, plugins).await
}
async fn send_to_plugins_and_wait(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
payload: &InternalEventPayload,
plugins: Vec<PluginHandle>,
) -> Result<Vec<InternalEvent>> {
@@ -380,7 +376,7 @@ impl PluginManager {
// 1. Build the events with IDs and everything
let events_to_send = plugins
.iter()
.map(|p| p.build_event_to_send(window_context, payload, None))
.map(|p| p.build_event_to_send(plugin_context, payload, None))
.collect::<Vec<InternalEvent>>();
// 2. Spawn thread to subscribe to incoming events and check reply ids
@@ -433,7 +429,7 @@ impl PluginManager {
) -> Result<Vec<GetThemesResponse>> {
let reply_events = self
.send_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&InternalEventPayload::GetThemesRequest(GetThemesRequest {}),
)
.await?;
@@ -454,7 +450,7 @@ impl PluginManager {
) -> Result<Vec<GetGrpcRequestActionsResponse>> {
let reply_events = self
.send_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&InternalEventPayload::GetGrpcRequestActionsRequest(EmptyPayload {}),
)
.await?;
@@ -475,7 +471,7 @@ impl PluginManager {
) -> Result<Vec<GetHttpRequestActionsResponse>> {
let reply_events = self
.send_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&InternalEventPayload::GetHttpRequestActionsRequest(EmptyPayload {}),
)
.await?;
@@ -520,11 +516,11 @@ impl PluginManager {
Some(v) => v,
};
let window_context = &PluginWindowContext::new(&window);
let plugin_context = &PluginContext::new(&window);
let vars = &make_vars_hashmap(environment_chain);
let cb = PluginTemplateCallback::new(
window.app_handle(),
&window_context,
&plugin_context,
RenderPurpose::Preview,
);
// We don't want to fail for this op because the UI will not be able to list any auth types then
@@ -536,7 +532,7 @@ impl PluginManager {
let event = self
.send_to_plugin_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&plugin,
&InternalEventPayload::GetTemplateFunctionConfigRequest(
GetTemplateFunctionConfigRequest {
@@ -566,7 +562,7 @@ impl PluginManager {
let plugin =
self.get_plugin_by_ref_id(ref_id.as_str()).await.ok_or(PluginNotFoundErr(ref_id))?;
let event = plugin.build_event_to_send(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&InternalEventPayload::CallHttpRequestActionRequest(req),
None,
);
@@ -583,7 +579,7 @@ impl PluginManager {
let plugin =
self.get_plugin_by_ref_id(ref_id.as_str()).await.ok_or(PluginNotFoundErr(ref_id))?;
let event = plugin.build_event_to_send(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&InternalEventPayload::CallGrpcRequestActionRequest(req),
None,
);
@@ -595,10 +591,10 @@ impl PluginManager {
&self,
window: &WebviewWindow<R>,
) -> Result<Vec<(PluginHandle, GetHttpAuthenticationSummaryResponse)>> {
let window_context = PluginWindowContext::new(window);
let plugin_context = PluginContext::new(window);
let reply_events = self
.send_and_wait(
&window_context,
&plugin_context,
&InternalEventPayload::GetHttpAuthenticationSummaryRequest(EmptyPayload {}),
)
.await?;
@@ -635,7 +631,7 @@ impl PluginManager {
let vars = &make_vars_hashmap(environment_chain);
let cb = PluginTemplateCallback::new(
window.app_handle(),
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Preview,
);
// We don't want to fail for this op because the UI will not be able to list any auth types then
@@ -646,7 +642,7 @@ impl PluginManager {
let context_id = format!("{:x}", md5::compute(model_id.to_string()));
let event = self
.send_to_plugin_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&plugin,
&InternalEventPayload::GetHttpAuthenticationConfigRequest(
GetHttpAuthenticationConfigRequest {
@@ -681,7 +677,7 @@ impl PluginManager {
vars,
&PluginTemplateCallback::new(
window.app_handle(),
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Preview,
),
&RenderOptions {
@@ -697,7 +693,7 @@ impl PluginManager {
let context_id = format!("{:x}", md5::compute(model_id.to_string()));
self.send_to_plugin_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&plugin,
&InternalEventPayload::CallHttpAuthenticationActionRequest(
CallHttpAuthenticationActionRequest {
@@ -719,6 +715,7 @@ impl PluginManager {
window: &WebviewWindow<R>,
auth_name: &str,
req: CallHttpAuthenticationRequest,
plugin_context: &PluginContext,
) -> Result<CallHttpAuthenticationResponse> {
let disabled = match req.values.get("disabled") {
Some(JsonPrimitive::Boolean(v)) => v.clone(),
@@ -742,7 +739,7 @@ impl PluginManager {
let event = self
.send_to_plugin_and_wait(
&PluginWindowContext::new(window),
plugin_context,
&plugin,
&InternalEventPayload::CallHttpAuthenticationRequest(req),
)
@@ -761,10 +758,10 @@ impl PluginManager {
&self,
window: &WebviewWindow<R>,
) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
let window_context = PluginWindowContext::new(window);
let plugin_context = PluginContext::new(window);
let reply_events = self
.send_and_wait(
&window_context,
&plugin_context,
&InternalEventPayload::GetTemplateFunctionSummaryRequest(EmptyPayload {}),
)
.await?;
@@ -787,7 +784,7 @@ impl PluginManager {
pub async fn call_template_function(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
fn_name: &str,
values: HashMap<String, serde_json::Value>,
purpose: RenderPurpose,
@@ -798,7 +795,7 @@ impl PluginManager {
};
let events = self
.send_and_wait(window_context, &InternalEventPayload::CallTemplateFunctionRequest(req))
.send_and_wait(plugin_context, &InternalEventPayload::CallTemplateFunctionRequest(req))
.await
.map_err(|e| RenderError(format!("Failed to call template function {e:}")))?;
@@ -832,7 +829,7 @@ impl PluginManager {
) -> Result<ImportResponse> {
let reply_events = self
.send_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&InternalEventPayload::ImportRequest(ImportRequest {
content: content.to_string(),
}),
@@ -872,7 +869,7 @@ impl PluginManager {
let event = self
.send_to_plugin_and_wait(
&PluginWindowContext::new(window),
&PluginContext::new(window),
&plugin,
&InternalEventPayload::FilterRequest(FilterRequest {
filter: filter.to_string(),

View File

@@ -1,5 +1,5 @@
use crate::events::{
FormInput, FormInputBase, FormInputText, PluginWindowContext, RenderPurpose, TemplateFunction,
FormInput, FormInputBase, FormInputText, PluginContext, RenderPurpose, TemplateFunction,
TemplateFunctionArg,
};
use crate::template_callback::PluginTemplateCallback;
@@ -65,13 +65,10 @@ pub(crate) fn template_function_keyring() -> TemplateFunction {
pub fn template_function_secure_run<R: Runtime>(
app_handle: &AppHandle<R>,
args: HashMap<String, serde_json::Value>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
) -> Result<String> {
match window_context.clone() {
PluginWindowContext::Label {
workspace_id: Some(wid),
..
} => {
match plugin_context.workspace_id.clone() {
Some(wid) => {
let value = args.get("value").map(|v| v.to_owned()).unwrap_or_default();
let value = match value {
serde_json::Value::String(s) => s,
@@ -97,13 +94,13 @@ pub fn template_function_secure_run<R: Runtime>(
let r = String::from_utf8(r).map_err(|e| RenderError(e.to_string()))?;
Ok(r)
}
_ => Err(RenderError("workspace_id missing from window context".to_string())),
_ => Err(RenderError("workspace_id missing from plugin context".to_string())),
}
}
pub fn template_function_secure_transform_arg<R: Runtime>(
app_handle: &AppHandle<R>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
arg_name: &str,
arg_value: &str,
) -> Result<String> {
@@ -111,11 +108,8 @@ pub fn template_function_secure_transform_arg<R: Runtime>(
return Ok(arg_value.to_string());
}
match window_context.clone() {
PluginWindowContext::Label {
workspace_id: Some(wid),
..
} => {
match plugin_context.workspace_id.clone() {
Some(wid) => {
if arg_value.is_empty() {
return Ok("".to_string());
}
@@ -132,13 +126,13 @@ pub fn template_function_secure_transform_arg<R: Runtime>(
let r = BASE64_STANDARD.encode(r);
Ok(format!("YENC_{}", r))
}
_ => Err(RenderError("workspace_id missing from window context".to_string())),
_ => Err(RenderError("workspace_id missing from plugin context".to_string())),
}
}
pub fn decrypt_secure_template_function<R: Runtime>(
app_handle: &AppHandle<R>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
template: &str,
) -> Result<String> {
let mut parsed = Parser::new(template).parse()?;
@@ -159,7 +153,7 @@ pub fn decrypt_secure_template_function<R: Runtime>(
}
}
new_tokens.push(Token::Raw {
text: template_function_secure_run(app_handle, args_map, window_context)?,
text: template_function_secure_run(app_handle, args_map, plugin_context)?,
});
}
t => {
@@ -175,10 +169,10 @@ pub fn decrypt_secure_template_function<R: Runtime>(
pub fn encrypt_secure_template_function<R: Runtime>(
app_handle: &AppHandle<R>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
template: &str,
) -> Result<String> {
let decrypted = decrypt_secure_template_function(&app_handle, window_context, template)?;
let decrypted = decrypt_secure_template_function(&app_handle, plugin_context, template)?;
let tokens = Tokens {
tokens: vec![Token::Tag {
val: Val::Fn {
@@ -193,7 +187,7 @@ pub fn encrypt_secure_template_function<R: Runtime>(
Ok(transform_args(
tokens,
&PluginTemplateCallback::new(app_handle, window_context, RenderPurpose::Preview),
&PluginTemplateCallback::new(app_handle, plugin_context, RenderPurpose::Preview),
)?
.to_string())
}

View File

@@ -1,5 +1,5 @@
use crate::error::Result;
use crate::events::{InternalEvent, InternalEventPayload, PluginWindowContext};
use crate::events::{InternalEvent, InternalEventPayload, PluginContext};
use crate::plugin_meta::{PluginMetadata, get_plugin_meta};
use crate::util::gen_id;
use std::path::Path;
@@ -33,16 +33,16 @@ impl PluginHandle {
pub fn build_event_to_send(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
payload: &InternalEventPayload,
reply_id: Option<String>,
) -> InternalEvent {
self.build_event_to_send_raw(window_context, payload, reply_id)
self.build_event_to_send_raw(plugin_context, payload, reply_id)
}
pub(crate) fn build_event_to_send_raw(
&self,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
payload: &InternalEventPayload,
reply_id: Option<String>,
) -> InternalEvent {
@@ -53,7 +53,7 @@ impl PluginHandle {
plugin_name: dir.file_name().unwrap().to_str().unwrap().to_string(),
reply_id,
payload: payload.clone(),
window_context: window_context.clone(),
context: plugin_context.clone(),
}
}

View File

@@ -76,10 +76,11 @@ impl PluginRuntimeServerWebsocket {
return;
}
let event = match serde_json::from_str::<InternalEventRawPayload>(&msg.into_text().unwrap()) {
let msg_text = msg.into_text().unwrap();
let event = match serde_json::from_str::<InternalEventRawPayload>(&msg_text) {
Ok(e) => e,
Err(e) => {
error!("Failed to decode plugin event {e:?}");
error!("Failed to decode plugin event {e:?} -> {msg_text}");
continue;
}
};
@@ -98,7 +99,7 @@ impl PluginRuntimeServerWebsocket {
payload,
plugin_ref_id: event.plugin_ref_id,
plugin_name: event.plugin_name,
window_context: event.window_context,
context: event.context,
reply_id: event.reply_id,
};

View File

@@ -1,4 +1,4 @@
use crate::events::{PluginWindowContext, RenderPurpose};
use crate::events::{PluginContext, RenderPurpose};
use crate::manager::PluginManager;
use crate::native_template_functions::{
template_function_keychain_run, template_function_secure_run,
@@ -13,19 +13,19 @@ use yaak_templates::error::Result;
pub struct PluginTemplateCallback<R: Runtime> {
app_handle: AppHandle<R>,
render_purpose: RenderPurpose,
window_context: PluginWindowContext,
plugin_context: PluginContext,
}
impl<R: Runtime> PluginTemplateCallback<R> {
pub fn new(
app_handle: &AppHandle<R>,
window_context: &PluginWindowContext,
plugin_context: &PluginContext,
render_purpose: RenderPurpose,
) -> PluginTemplateCallback<R> {
PluginTemplateCallback {
render_purpose,
app_handle: app_handle.to_owned(),
window_context: window_context.to_owned(),
plugin_context: plugin_context.to_owned(),
}
}
}
@@ -37,7 +37,7 @@ impl<R: Runtime> TemplateCallback for PluginTemplateCallback<R> {
let fn_name = if fn_name == "Response" { "response" } else { fn_name };
if fn_name == "secure" {
return template_function_secure_run(&self.app_handle, args, &self.window_context);
return template_function_secure_run(&self.app_handle, args, &self.plugin_context);
} else if fn_name == "keychain" || fn_name == "keyring" {
return template_function_keychain_run(args);
}
@@ -45,7 +45,7 @@ impl<R: Runtime> TemplateCallback for PluginTemplateCallback<R> {
let plugin_manager = &*self.app_handle.state::<PluginManager>();
let resp = plugin_manager
.call_template_function(
&self.window_context,
&self.plugin_context,
fn_name,
args,
self.render_purpose.to_owned(),
@@ -58,7 +58,7 @@ impl<R: Runtime> TemplateCallback for PluginTemplateCallback<R> {
if fn_name == "secure" {
return template_function_secure_transform_arg(
&self.app_handle,
&self.window_context,
&self.plugin_context,
arg_name,
arg_value,
);

View File

@@ -8,7 +8,7 @@ publish = false
[dependencies]
chrono = { workspace = true, features = ["serde"] }
hex = { workspace = true }
log = "0.4.22"
log = { workspace = true }
notify = "8.0.0"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }

View File

@@ -19,4 +19,4 @@ tokio = { workspace = true, features = ["macros", "rt"] }
ts-rs = { workspace = true }
wasm-bindgen = { version = "0.2.100", features = ["serde-serialize"] }
serde-wasm-bindgen = "0.6.5"
log = "0.4.27"
log = { workspace = true }

View File

@@ -7,7 +7,7 @@ publish = false
[dependencies]
futures-util = "0.3.31"
log = "0.4.20"
log = { workspace = true }
md5 = "0.7.0"
reqwest_cookie_store = { workspace = true }
serde = { workspace = true, features = ["derive"] }

View File

@@ -10,7 +10,7 @@ use tauri::{AppHandle, Runtime, State, Url, WebviewWindow};
use tokio::sync::{Mutex, mpsc};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use yaak_http::apply_path_placeholders;
use yaak_http::path_placeholders::apply_path_placeholders;
use yaak_models::models::{
HttpResponseHeader, WebsocketConnection, WebsocketConnectionState, WebsocketEvent,
WebsocketEventType, WebsocketRequest,
@@ -18,7 +18,7 @@ use yaak_models::models::{
use yaak_models::query_manager::QueryManagerExt;
use yaak_models::util::UpdateSource;
use yaak_plugins::events::{
CallHttpAuthenticationRequest, HttpHeader, PluginWindowContext, RenderPurpose,
CallHttpAuthenticationRequest, HttpHeader, PluginContext, RenderPurpose,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback;
@@ -124,7 +124,7 @@ pub(crate) async fn send<R: Runtime>(
environment_chain,
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Send,
),
&RenderOptions {
@@ -203,7 +203,7 @@ pub(crate) async fn connect<R: Runtime>(
environment_chain,
&PluginTemplateCallback::new(
&app_handle,
&PluginWindowContext::new(&window),
&PluginContext::new(&window),
RenderPurpose::Send,
),
&RenderOptions {
@@ -283,7 +283,12 @@ pub(crate) async fn connect<R: Runtime>(
.collect(),
};
let plugin_result = plugin_manager
.call_http_authentication(&window, &authentication_type, plugin_req)
.call_http_authentication(
&window,
&authentication_type,
plugin_req,
&PluginContext::new(&window),
)
.await?;
for header in plugin_result.set_headers.unwrap_or_default() {
match (HeaderName::from_str(&header.name), HeaderValue::from_str(&header.value)) {