mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-30 20:14:01 +01:00
Merge main into feat/request-versioning
Conflicts were all at registration points; both sides are kept. Main now routes every write through one connection (#642): ClientDb only reads and writes go through `with_tx` on a WriteDb. Versioning follows: snapshot, restore, prune and the cascade delete move to WriteDb, while the lookups and the "has it changed" check stay on ClientDb. Callers take a write transaction the way their neighbours do: - The HTTP send snapshots in its own transaction from `resolve_send_inputs`, and a failure there (including not getting the writer) is still logged and swallowed, so the response just has no version. - gRPC and WebSocket connect snapshot inside the transaction that upserts the connection. - The snapshot and restore RPCs, on the desktop and in the browser host, each run in a transaction. - The request and workspace cascades live on main's WriteDb deletes. The Request Changed dropdown moves into the response pane's `statusLineRight` slot, since main moved the status line into the shared pane view. The plugin runtime's copy of the model bindings picks up `versionId`, and `gen_rpc.ts` is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
1b0a196c50
794 files changed
+76953
-18061
No files matched your search
@@ -28,7 +28,7 @@ openssl-sys = { version = "0.9.105", features = ["vendored"] } # For Ubuntu inst
|
||||
rlimit = "0.11" # Raise the launchd 256 open-file soft limit at startup
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22.1" # For writing values the editor only ever held encoded
|
||||
base64 = "0.23.1" # For writing values the editor only ever held encoded
|
||||
charset = "0.1.5"
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
cookie = "0.18.1"
|
||||
@@ -41,14 +41,15 @@ pretty_graphql = "0.2"
|
||||
r2d2 = "0.8.10"
|
||||
r2d2_sqlite = "0.32"
|
||||
mime_guess = "2.0.5"
|
||||
rand = "0.9.0"
|
||||
rand = "0.10.2"
|
||||
reqwest = { workspace = true, features = [
|
||||
"multipart",
|
||||
"gzip",
|
||||
"brotli",
|
||||
"deflate",
|
||||
"json",
|
||||
"rustls-tls-manual-roots-no-provider",
|
||||
"query",
|
||||
"rustls-no-provider",
|
||||
"socks",
|
||||
"http2",
|
||||
] }
|
||||
@@ -68,7 +69,7 @@ tauri-plugin-updater = "2.10.1"
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
tokio-stream = "0.1.17"
|
||||
tokio-tungstenite = { version = "0.26.2", default-features = false }
|
||||
tokio-tungstenite = { version = "0.30.0", default-features = false }
|
||||
url = "2"
|
||||
tokio-util = { version = "0.7", features = ["codec"] }
|
||||
ts-rs = { workspace = true }
|
||||
@@ -82,6 +83,7 @@ yaak-core = { workspace = true }
|
||||
yaak = { workspace = true }
|
||||
yaak-commands = { workspace = true }
|
||||
yaak-crypto = { workspace = true }
|
||||
yaak-filter = { workspace = true }
|
||||
yaak-fonts = { workspace = true }
|
||||
yaak-git = { workspace = true }
|
||||
yaak-grpc = { workspace = true }
|
||||
@@ -89,6 +91,7 @@ yaak-http = { workspace = true }
|
||||
yaak-license = { workspace = true, optional = true }
|
||||
yaak-mac-window = { workspace = true }
|
||||
yaak-lifecycle = { workspace = true }
|
||||
yaak-mcp = { workspace = true }
|
||||
yaak-models = { workspace = true }
|
||||
yaak-plugins = { workspace = true }
|
||||
yaak-sse = { workspace = true }
|
||||
|
||||
+2
@@ -1,5 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type NavigateWorkspace = { workspaceId: string; environmentId: string | null };
|
||||
|
||||
export type PluginUpdateInfo = { name: string; currentVersion: string; latestVersion: string };
|
||||
|
||||
export type PluginUpdateNotification = { updateCount: number; plugins: Array<PluginUpdateInfo> };
|
||||
|
||||
@@ -19,7 +19,6 @@ pub(crate) fn metadata_to_map(metadata: MetadataMap) -> BTreeMap<String, String>
|
||||
entries
|
||||
}
|
||||
|
||||
|
||||
pub(crate) async fn build_metadata<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
request: &GrpcRequest,
|
||||
|
||||
@@ -177,4 +177,3 @@ async fn send_http_request_inner<R: Runtime>(
|
||||
|
||||
Ok(SentHttpRequest { response: result.response, body: result.response_body })
|
||||
}
|
||||
|
||||
@@ -1,46 +1,89 @@
|
||||
use crate::PluginContextExt;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::models_ext::QueryManagerExt;
|
||||
use std::fs::read_to_string;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
use tauri::{Manager, Runtime, WebviewWindow};
|
||||
use yaak::import::{self, PlanImportDataParams};
|
||||
use yaak_api::{ApiClientKind, yaak_api_client};
|
||||
use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportOrigin, ImportPlan};
|
||||
use yaak_plugins::MAX_IMPORT_BYTES;
|
||||
use yaak_plugins::events::ImportRequest;
|
||||
|
||||
pub(crate) async fn import_data<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
file_path: &str,
|
||||
origin: Option<ImportOrigin>,
|
||||
) -> Result<BatchUpsertResult> {
|
||||
let contents = read_import_file(file_path)?;
|
||||
let input = read_import_file(file_path)?;
|
||||
let plan =
|
||||
plan_import_contents(window, &contents, ImportDestination::NewWorkspace, origin).await?;
|
||||
plan_import_contents(window, &input, ImportDestination::NewWorkspace, origin).await?;
|
||||
commit_import(window, plan)
|
||||
}
|
||||
|
||||
pub(crate) async fn plan_import_data<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
file_path: &str,
|
||||
file_paths: &[String],
|
||||
urls: &[String],
|
||||
destination: ImportDestination,
|
||||
) -> Result<ImportPlan> {
|
||||
let contents = read_import_file(file_path)?;
|
||||
plan_import_contents(window, &contents, destination, Some(file_origin(file_path))).await
|
||||
let plugin_manager = crate::plugins_ext::plugin_manager(window).await?;
|
||||
let plugin_context = window.plugin_context();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut inputs = Vec::new();
|
||||
for path in file_paths {
|
||||
let origin = file_origin(path);
|
||||
if !seen.insert(origin.origin.clone()) {
|
||||
continue;
|
||||
}
|
||||
let input = read_import_file(path)?;
|
||||
let response = plugin_manager
|
||||
.import_input(&plugin_context, &input)
|
||||
.await
|
||||
.map_err(|err| Error::GenericError(format!("Unable to import {path}: {err}")))?;
|
||||
inputs.push((response, origin));
|
||||
}
|
||||
for url in urls {
|
||||
let url = normalize_import_url(url)?;
|
||||
if !seen.insert(url.clone()) {
|
||||
continue;
|
||||
}
|
||||
let input = fetch_import_url(window, &url).await?;
|
||||
let response = plugin_manager
|
||||
.import_input(&plugin_context, &input)
|
||||
.await
|
||||
.map_err(|err| Error::GenericError(format!("Unable to import {url}: {err}")))?;
|
||||
inputs.push((response, url_origin(&url)));
|
||||
}
|
||||
Ok(import::plan_import_batch_resources(&window.db_manager(), destination, inputs)?)
|
||||
}
|
||||
|
||||
pub(crate) async fn plan_import_url<R: Runtime>(
|
||||
/// Which importer claims a source, without planning it. Backs the per-source status in the
|
||||
/// import dialog so unsupported files are flagged before preview.
|
||||
pub(crate) async fn detect_import_source<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
url: &str,
|
||||
destination: ImportDestination,
|
||||
) -> Result<ImportPlan> {
|
||||
let url = normalize_import_url(url)?;
|
||||
let contents = fetch_import_url(window, &url).await?;
|
||||
plan_import_contents(window, &contents, destination, Some(url_origin(&url))).await
|
||||
file_path: Option<String>,
|
||||
url: Option<String>,
|
||||
) -> Result<String> {
|
||||
let input = match (file_path, url) {
|
||||
(Some(path), _) => read_import_file(&path)?,
|
||||
(None, Some(url)) => fetch_import_url(window, &normalize_import_url(&url)?).await?,
|
||||
(None, None) => return Err(Error::GenericError("Nothing to detect".into())),
|
||||
};
|
||||
let plugin_manager = crate::plugins_ext::plugin_manager(window).await?;
|
||||
let response = plugin_manager.import_input(&window.plugin_context(), &input).await.map_err(
|
||||
|err| match err {
|
||||
yaak_plugins::error::Error::PluginErr(msg) if msg.starts_with("No importers found") => {
|
||||
Error::GenericError("Not a supported format".into())
|
||||
}
|
||||
err => Error::GenericError(err.to_string()),
|
||||
},
|
||||
)?;
|
||||
Ok(response.importer)
|
||||
}
|
||||
|
||||
async fn plan_import_contents<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
contents: &str,
|
||||
input: &ImportRequest,
|
||||
destination: ImportDestination,
|
||||
origin: Option<ImportOrigin>,
|
||||
) -> Result<ImportPlan> {
|
||||
@@ -53,7 +96,7 @@ async fn plan_import_contents<R: Runtime>(
|
||||
plugin_manager: &plugin_manager,
|
||||
plugin_context: &plugin_context,
|
||||
destination,
|
||||
contents,
|
||||
input,
|
||||
origin,
|
||||
})
|
||||
.await?)
|
||||
@@ -88,7 +131,10 @@ pub(crate) fn commit_import<R: Runtime>(
|
||||
/// This uses Yaak's own API client, which follows the OS proxy but not the workspace's proxy,
|
||||
/// client certificate, or certificate-validation settings. Requests are unauthenticated, so
|
||||
/// specs behind auth must still be downloaded manually and imported as a file.
|
||||
async fn fetch_import_url<R: Runtime>(window: &WebviewWindow<R>, url: &str) -> Result<String> {
|
||||
async fn fetch_import_url<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
url: &str,
|
||||
) -> Result<ImportRequest> {
|
||||
let url = normalize_import_url(url)?;
|
||||
let app_version = window.app_handle().package_info().version.to_string();
|
||||
let response = yaak_api_client(ApiClientKind::App, &app_version)?
|
||||
@@ -104,10 +150,27 @@ async fn fetch_import_url<R: Runtime>(window: &WebviewWindow<R>, url: &str) -> R
|
||||
return Err(Error::GenericError(format!("Failed to fetch {url}: responded with {status}")));
|
||||
}
|
||||
|
||||
response
|
||||
.text()
|
||||
// Apply the same input-size limit to downloads before allocating the whole body.
|
||||
let mut response = response;
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.map_err(|err| Error::GenericError(format!("Failed to read response from {url}: {err}")))
|
||||
.map_err(|err| Error::GenericError(format!("Failed to read response from {url}: {err}")))?
|
||||
{
|
||||
if (bytes.len() + chunk.len()) as u64 > MAX_IMPORT_BYTES {
|
||||
return Err(Error::GenericError("Import file exceeds the 64 MiB limit".into()));
|
||||
}
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
let name = reqwest::Url::parse(&url)
|
||||
.ok()
|
||||
.and_then(|url| {
|
||||
url.path_segments().and_then(|mut segments| segments.next_back().map(str::to_owned))
|
||||
})
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "download".into());
|
||||
ImportRequest::from_bytes(&name, &bytes).map_err(|err| Error::GenericError(err.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_import_url(url: &str) -> Result<String> {
|
||||
@@ -128,15 +191,9 @@ pub(crate) fn normalize_import_url(url: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_import_file(file_path: &str) -> Result<String> {
|
||||
read_to_string(file_path).map_err(|err| {
|
||||
if err.kind() == ErrorKind::InvalidData {
|
||||
Error::GenericError(format!(
|
||||
"Import file must be UTF-8 text; binary files are not supported: {file_path}"
|
||||
))
|
||||
} else {
|
||||
Error::GenericError(format!("Unable to read import file {file_path}: {err}"))
|
||||
}
|
||||
fn read_import_file(file_path: &str) -> Result<ImportRequest> {
|
||||
ImportRequest::from_path(Path::new(file_path)).map_err(|err| {
|
||||
Error::GenericError(format!("Unable to read import source {file_path}: {err}"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -147,7 +204,7 @@ mod tests {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[test]
|
||||
fn read_import_file_returns_error_for_binary_file() {
|
||||
fn read_import_file_accepts_binary_file() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"yaak-import-binary-{}.pftrace",
|
||||
SystemTime::now()
|
||||
@@ -157,10 +214,11 @@ mod tests {
|
||||
));
|
||||
write(&path, [0xff, 0xfe, 0xfd]).expect("write binary fixture");
|
||||
|
||||
let err = read_import_file(path.to_str().expect("temp path is utf-8"))
|
||||
.expect_err("binary import should return an error");
|
||||
let input = read_import_file(path.to_str().expect("temp path is utf-8"))
|
||||
.expect("binary import should preserve bytes");
|
||||
|
||||
assert!(err.to_string().contains("binary files are not supported"));
|
||||
assert!(input.source.is_some());
|
||||
assert!(input.content.is_empty());
|
||||
|
||||
remove_file(path).expect("remove binary fixture");
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::error::Error::GenericError;
|
||||
use crate::error::Result;
|
||||
use crate::grpc::{build_metadata, metadata_to_map};
|
||||
use crate::http_request::send_http_request;
|
||||
use crate::import::{commit_import, plan_import_data, plan_import_url};
|
||||
use crate::import::{commit_import, plan_import_data};
|
||||
use crate::models_ext::{BlobManagerExt, QueryManagerExt};
|
||||
use crate::notifications::YaakNotifier;
|
||||
use crate::render::{render_grpc_request, render_template};
|
||||
@@ -29,16 +29,16 @@ use tokio::sync::Mutex;
|
||||
use tokio::task::block_in_place;
|
||||
use tokio::time;
|
||||
use yaak::send::ResponseBody;
|
||||
use yaak_commands::responses::locate_response_body;
|
||||
use yaak_commands::resolve::resolve_grpc_request;
|
||||
use yaak_commands::responses::locate_response_body;
|
||||
use yaak_common::command::new_checked_command;
|
||||
use yaak_crypto::manager::EncryptionManager;
|
||||
use yaak_grpc::manager::{GrpcConfig, GrpcHandle};
|
||||
use yaak_grpc::{Code, ServiceDefinition};
|
||||
use yaak_mac_window::AppHandleMacWindowExt;
|
||||
use yaak_models::models::{
|
||||
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent,
|
||||
GrpcEventType, HttpRequest, HttpResponse, HttpResponseState, Workspace,
|
||||
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent, GrpcEventType,
|
||||
HttpRequest, HttpResponse, HttpResponseState, Workspace,
|
||||
};
|
||||
use yaak_models::queries::any_request::AnyRequest;
|
||||
use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan, UpdateSource};
|
||||
@@ -138,6 +138,7 @@ fn setup_window_menu<R: Runtime>(win: &WebviewWindow<R>) -> Result<()> {
|
||||
"dev.generate_theme_css" => {
|
||||
w.emit("generate_theme_css", true).unwrap();
|
||||
}
|
||||
"dev.show_home" => w.emit("show_home", true).unwrap(),
|
||||
"dev.toggle_devtools" => {
|
||||
if webview_window.is_devtools_open() {
|
||||
webview_window.close_devtools();
|
||||
@@ -331,25 +332,25 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let settings = app_handle.db().get_settings();
|
||||
let client_cert = find_client_certificate(&request.url, &settings.client_certificates);
|
||||
|
||||
// Capture the stored request, not the rendered one: what a restore should
|
||||
// put back is what the user typed
|
||||
let version_id = app_handle
|
||||
.db()
|
||||
.snapshot_request_for_send(&AnyRequest::GrpcRequest(unrendered_request.clone()));
|
||||
|
||||
let conn = app_handle.db().upsert_grpc_connection(
|
||||
&GrpcConnection {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
request_id: request.id.clone(),
|
||||
status: -1,
|
||||
elapsed: 0,
|
||||
state: GrpcConnectionState::Initialized,
|
||||
url: request.url.clone(),
|
||||
version_id,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
let conn = app_handle.with_tx(|tx| {
|
||||
// Capture the stored request, not the rendered one: what a restore should
|
||||
// put back is what the user typed
|
||||
let version_id =
|
||||
tx.snapshot_request_for_send(&AnyRequest::GrpcRequest(unrendered_request.clone()));
|
||||
tx.upsert_grpc_connection(
|
||||
&GrpcConnection {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
request_id: request.id.clone(),
|
||||
status: -1,
|
||||
elapsed: 0,
|
||||
state: GrpcConnectionState::Initialized,
|
||||
url: request.url.clone(),
|
||||
version_id,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let conn_id = conn.id.clone();
|
||||
|
||||
@@ -394,15 +395,17 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let connection = match connection {
|
||||
Ok(c) => c,
|
||||
Err(err) => {
|
||||
app_handle.db().upsert_grpc_connection(
|
||||
&GrpcConnection {
|
||||
elapsed: start.elapsed().as_millis() as i32,
|
||||
error: Some(err.to_string()),
|
||||
state: GrpcConnectionState::Closed,
|
||||
..conn.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.upsert_grpc_connection(
|
||||
&GrpcConnection {
|
||||
elapsed: start.elapsed().as_millis() as i32,
|
||||
error: Some(err.to_string()),
|
||||
state: GrpcConnectionState::Closed,
|
||||
..conn.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
return Ok(conn_id);
|
||||
}
|
||||
};
|
||||
@@ -503,15 +506,17 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
.await?;
|
||||
let msg = strip_json_comments(&msg);
|
||||
|
||||
app_handle.db().upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: format!("Connecting to {}", req.url),
|
||||
event_type: GrpcEventType::ConnectionStart,
|
||||
metadata: metadata.clone(),
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: format!("Connecting to {}", req.url),
|
||||
event_type: GrpcEventType::ConnectionStart,
|
||||
metadata: metadata.clone(),
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
async move {
|
||||
// Create callback for streaming methods that handles both success and error
|
||||
@@ -521,24 +526,28 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let window_label = window.label().to_string();
|
||||
move |result: std::result::Result<String, String>| match result {
|
||||
Ok(msg) => {
|
||||
let _ = app_handle.db().upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: msg,
|
||||
event_type: GrpcEventType::ClientMessage,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
);
|
||||
let _ = app_handle.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: msg,
|
||||
event_type: GrpcEventType::ClientMessage,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = app_handle.db().upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: format!("Failed to send message: {}", error),
|
||||
event_type: GrpcEventType::Error,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
);
|
||||
let _ = app_handle.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: format!("Failed to send message: {}", error),
|
||||
event_type: GrpcEventType::Error,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -591,36 +600,38 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
|
||||
if !method_desc.is_client_streaming() {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
event_type: GrpcEventType::ClientMessage,
|
||||
content: msg,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
event_type: GrpcEventType::ClientMessage,
|
||||
content: msg,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
match maybe_msg {
|
||||
Some(Ok(msg)) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
metadata: metadata_to_map(msg.metadata().clone()),
|
||||
content: if msg.metadata().len() == 0 {
|
||||
"Received response"
|
||||
} else {
|
||||
"Received response with metadata"
|
||||
}
|
||||
.to_string(),
|
||||
event_type: GrpcEventType::Info,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
metadata: metadata_to_map(msg.metadata().clone()),
|
||||
content: if msg.metadata().len() == 0 {
|
||||
"Received response"
|
||||
} else {
|
||||
"Received response with metadata"
|
||||
}
|
||||
.to_string(),
|
||||
event_type: GrpcEventType::Info,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let response_message = msg.into_inner();
|
||||
let content = match connection
|
||||
@@ -630,83 +641,88 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
Ok(content) => content,
|
||||
Err(err) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Failed to read response".to_string(),
|
||||
error: Some(err.to_string()),
|
||||
status: Some(Code::Internal as i32),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Failed to read response".to_string(),
|
||||
error: Some(err.to_string()),
|
||||
status: Some(Code::Internal as i32),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
return;
|
||||
}
|
||||
};
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content,
|
||||
event_type: GrpcEventType::ServerMessage,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content,
|
||||
event_type: GrpcEventType::ServerMessage,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Connection complete".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
status: Some(Code::Ok as i32),
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Connection complete".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
status: Some(Code::Ok as i32),
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&(match e.status {
|
||||
Some(s) => GrpcEvent {
|
||||
error: Some(s.message().to_string()),
|
||||
status: Some(s.code() as i32),
|
||||
content: "Request failed".to_string(),
|
||||
metadata: metadata_to_map(s.metadata().clone()),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
None => GrpcEvent {
|
||||
error: Some(e.message),
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&(match e.status {
|
||||
Some(s) => GrpcEvent {
|
||||
error: Some(s.message().to_string()),
|
||||
status: Some(s.code() as i32),
|
||||
content: "Request failed".to_string(),
|
||||
metadata: metadata_to_map(s.metadata().clone()),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
None => GrpcEvent {
|
||||
error: Some(e.message),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Request failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
}),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
app_handle
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
error: Some(e.to_string()),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Request failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
}),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
error: Some(e.to_string()),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Request failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
None => {
|
||||
@@ -717,64 +733,67 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let mut stream = match maybe_stream {
|
||||
Some(Ok(stream)) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
metadata: metadata_to_map(stream.metadata().clone()),
|
||||
content: if stream.metadata().len() == 0 {
|
||||
"Received response"
|
||||
} else {
|
||||
"Received response with metadata"
|
||||
}
|
||||
.to_string(),
|
||||
event_type: GrpcEventType::Info,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
metadata: metadata_to_map(stream.metadata().clone()),
|
||||
content: if stream.metadata().len() == 0 {
|
||||
"Received response"
|
||||
} else {
|
||||
"Received response with metadata"
|
||||
}
|
||||
.to_string(),
|
||||
event_type: GrpcEventType::Info,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
stream.into_inner()
|
||||
}
|
||||
Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
|
||||
warn!("GRPC stream error {e:?}");
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&(match e.status {
|
||||
Some(s) => GrpcEvent {
|
||||
error: Some(s.message().to_string()),
|
||||
status: Some(s.code() as i32),
|
||||
content: "Stream failed".to_string(),
|
||||
metadata: metadata_to_map(s.metadata().clone()),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
None => GrpcEvent {
|
||||
error: Some(e.message),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Stream failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
}),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&(match e.status {
|
||||
Some(s) => GrpcEvent {
|
||||
error: Some(s.message().to_string()),
|
||||
status: Some(s.code() as i32),
|
||||
content: "Stream failed".to_string(),
|
||||
metadata: metadata_to_map(s.metadata().clone()),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
None => GrpcEvent {
|
||||
error: Some(e.message),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Stream failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
}),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
return;
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
error: Some(e.to_string()),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Stream failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
error: Some(e.to_string()),
|
||||
status: Some(Code::Unknown as i32),
|
||||
content: "Stream failed".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
return;
|
||||
}
|
||||
@@ -791,65 +810,69 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
Ok(message) => message,
|
||||
Err(err) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Failed to read response".to_string(),
|
||||
error: Some(err.to_string()),
|
||||
status: Some(Code::Internal as i32),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Failed to read response".to_string(),
|
||||
error: Some(err.to_string()),
|
||||
status: Some(Code::Internal as i32),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
break;
|
||||
}
|
||||
};
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: message,
|
||||
event_type: GrpcEventType::ServerMessage,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: message,
|
||||
event_type: GrpcEventType::ServerMessage,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
Ok(None) => {
|
||||
let trailers =
|
||||
stream.trailers().await.unwrap_or_default().unwrap_or_default();
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Connection complete".to_string(),
|
||||
status: Some(Code::Ok as i32),
|
||||
metadata: metadata_to_map(trailers),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Connection complete".to_string(),
|
||||
status: Some(Code::Ok as i32),
|
||||
metadata: metadata_to_map(trailers),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
break;
|
||||
}
|
||||
Err(status) => {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Stream failed".to_string(),
|
||||
error: Some(status.message().to_string()),
|
||||
status: Some(status.code() as i32),
|
||||
metadata: metadata_to_map(status.metadata().clone()),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Stream failed".to_string(),
|
||||
error: Some(status.message().to_string()),
|
||||
status: Some(status.code() as i32),
|
||||
metadata: metadata_to_map(status.metadata().clone()),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
..base_event.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
break;
|
||||
}
|
||||
@@ -882,21 +905,24 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
}).unwrap();
|
||||
},
|
||||
_ = cancelled_rx.changed() => {
|
||||
w.db().upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Cancelled".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
status: Some(Code::Cancelled as i32),
|
||||
..base_msg.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
).unwrap();
|
||||
w.with_tx(|tx| {
|
||||
tx.upsert_grpc_event(
|
||||
&GrpcEvent {
|
||||
content: "Cancelled".to_string(),
|
||||
event_type: GrpcEventType::ConnectionEnd,
|
||||
status: Some(Code::Cancelled as i32),
|
||||
..base_msg.clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
w.with_tx(|c| {
|
||||
c.upsert_grpc_connection(
|
||||
&GrpcConnection{
|
||||
elapsed: start.elapsed().as_millis() as i32,
|
||||
status: Code::Cancelled as i32,
|
||||
state: GrpcConnectionState::Closed,
|
||||
elapsed: start.elapsed().as_millis() as i32,
|
||||
status: Code::Cancelled as i32,
|
||||
state: GrpcConnectionState::Closed,
|
||||
..c.get_grpc_connection( &conn_id).unwrap().clone()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
@@ -983,10 +1009,11 @@ async fn cmd_http_response_body<R: Runtime>(
|
||||
.ok_or(GenericError("Failed to find response body".to_string()))?;
|
||||
|
||||
match filter {
|
||||
Some(filter) if !filter.is_empty() => Ok(plugins_ext::plugin_manager(&window)
|
||||
.await?
|
||||
.filter_data(&window.plugin_context(), filter, &body, content_type)
|
||||
.await?),
|
||||
Some(filter) if !filter.is_empty() => {
|
||||
let language = yaak_filter::Language::for_content_type(content_type);
|
||||
let result = yaak_filter::filter(language, &body, filter);
|
||||
Ok(FilterResponse { content: result.content, error: result.error })
|
||||
}
|
||||
_ => Ok(FilterResponse { content: body, error: None }),
|
||||
}
|
||||
}
|
||||
@@ -1020,18 +1047,11 @@ async fn cmd_get_sse_events<R: Runtime>(
|
||||
|
||||
async fn cmd_import_data<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
file_path: &str,
|
||||
file_paths: &[String],
|
||||
urls: &[String],
|
||||
destination: ImportDestination,
|
||||
) -> YaakResult<ImportPlan> {
|
||||
plan_import_data(&window, file_path, destination).await
|
||||
}
|
||||
|
||||
async fn cmd_import_url<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
url: &str,
|
||||
destination: ImportDestination,
|
||||
) -> YaakResult<ImportPlan> {
|
||||
plan_import_url(&window, url, destination).await
|
||||
plan_import_data(&window, file_paths, urls, destination).await
|
||||
}
|
||||
|
||||
async fn cmd_commit_import<R: Runtime>(
|
||||
@@ -1041,20 +1061,6 @@ async fn cmd_commit_import<R: Runtime>(
|
||||
commit_import(&window, plan)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// Decodes base64 and writes the bytes to a file the user picked.
|
||||
///
|
||||
/// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app
|
||||
@@ -1088,15 +1094,17 @@ async fn cmd_send_http_request<R: Runtime>(
|
||||
let request = app_handle.db().get_http_request(&request_id)?;
|
||||
|
||||
let blobs = app_handle.blob_manager();
|
||||
let response = app_handle.db().upsert_http_response(
|
||||
&HttpResponse {
|
||||
request_id: request.id.clone(),
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
&blobs,
|
||||
)?;
|
||||
let response = app_handle.with_tx(|tx| {
|
||||
tx.upsert_http_response(
|
||||
&HttpResponse {
|
||||
request_id: request.id.clone(),
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
&blobs,
|
||||
)
|
||||
})?;
|
||||
|
||||
let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
|
||||
app_handle.listen_any(format!("cancel_http_response_{}", response.id), move |_event| {
|
||||
@@ -1134,22 +1142,23 @@ async fn cmd_send_http_request<R: Runtime>(
|
||||
Ok(sent) => sent.response,
|
||||
Err(e) => {
|
||||
let resp = app_handle.db().get_http_response(&response.id)?;
|
||||
app_handle.db().upsert_http_response(
|
||||
&HttpResponse {
|
||||
state: HttpResponseState::Closed,
|
||||
error: Some(e.to_string()),
|
||||
..resp
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
&blobs,
|
||||
)?
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.upsert_http_response(
|
||||
&HttpResponse {
|
||||
state: HttpResponseState::Closed,
|
||||
error: Some(e.to_string()),
|
||||
..resp
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
&blobs,
|
||||
)
|
||||
})?
|
||||
}
|
||||
};
|
||||
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
async fn cmd_new_child_window<R: Runtime>(
|
||||
parent_window: WebviewWindow<R>,
|
||||
url: &str,
|
||||
@@ -1277,8 +1286,8 @@ pub fn run() {
|
||||
.setup(|app| {
|
||||
let lifecycle_host = yaak_lifecycle::Host::owner()
|
||||
.with_responses_dir(app.path().app_data_dir()?.join("responses"));
|
||||
if let Err(e) =
|
||||
yaak_lifecycle::on_launch(&lifecycle_host, &app.db(), &app.blob_manager())
|
||||
if let Err(e) = app
|
||||
.with_tx(|tx| yaak_lifecycle::on_launch(&lifecycle_host, tx, &app.blob_manager()))
|
||||
{
|
||||
error!("on_launch hook failed: {e:?}");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use tauri::plugin::TauriPlugin;
|
||||
use tauri::{Emitter, Manager, Runtime, State};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
|
||||
use yaak_models::blob_manager::BlobManager;
|
||||
use yaak_models::client_db::ClientDb;
|
||||
use yaak_models::client_db::{ClientDb, WriteDb};
|
||||
use yaak_models::error::Result;
|
||||
use yaak_models::query_manager::QueryManager;
|
||||
use yaak_models::util::{ModelPayload, UpdateSource};
|
||||
@@ -95,7 +95,7 @@ pub trait QueryManagerExt<'a, R> {
|
||||
fn db(&'a self) -> ClientDb<'a>;
|
||||
fn with_tx<F, T>(&'a self, func: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(&ClientDb) -> Result<T>;
|
||||
F: FnOnce(&WriteDb) -> Result<T>;
|
||||
}
|
||||
|
||||
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
||||
@@ -110,7 +110,7 @@ impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
||||
|
||||
fn with_tx<F, T>(&'a self, func: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(&ClientDb) -> Result<T>,
|
||||
F: FnOnce(&WriteDb) -> Result<T>,
|
||||
{
|
||||
let qm = self.state::<QueryManager>();
|
||||
qm.inner().with_tx(func)
|
||||
@@ -168,8 +168,10 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
|
||||
// Fast path for local app writes initiated by frontend windows. This keeps the
|
||||
// current sync-model UX snappy, while DB polling handles external writers (CLI).
|
||||
// A thread of its own: `recv` blocks, and a runtime worker parked in it strands
|
||||
// anything spawned from the loop in that worker's unstealable LIFO slot.
|
||||
let app_handle_local = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
std::thread::spawn(move || {
|
||||
while let Ok(payload) = rx.recv() {
|
||||
let mut batch: Vec<ModelPayload> = Vec::new();
|
||||
if matches!(payload.update_source, UpdateSource::Window { .. }) {
|
||||
|
||||
@@ -55,12 +55,15 @@ impl YaakNotifier {
|
||||
seen.push(id.to_string());
|
||||
debug!("Marked notification as seen {}", id);
|
||||
let seen_json = serde_json::to_string(&seen)?;
|
||||
window.db().set_key_value_raw(
|
||||
KV_NAMESPACE,
|
||||
KV_KEY,
|
||||
seen_json.as_str(),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
);
|
||||
window.with_tx(|tx| {
|
||||
tx.set_key_value_raw(
|
||||
KV_NAMESPACE,
|
||||
KV_KEY,
|
||||
seen_json.as_str(),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::error::Result;
|
||||
use crate::http_request::send_http_request_with_context;
|
||||
use crate::http_request::{SentHttpRequest, send_http_request_with_context};
|
||||
use crate::models_ext::BlobManagerExt;
|
||||
use crate::models_ext::QueryManagerExt;
|
||||
use crate::render::{render_grpc_request, render_http_request, render_json_value};
|
||||
@@ -12,7 +12,7 @@ use base64::prelude::BASE64_STANDARD;
|
||||
use chrono::Utc;
|
||||
use log::error;
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Emitter, Listener, Manager, Runtime};
|
||||
use tauri::{AppHandle, Emitter, Listener, Manager, Runtime, WebviewWindow};
|
||||
use tauri_plugin_clipboard_manager::ClipboardExt;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
use yaak::plugin_events::{
|
||||
@@ -21,7 +21,7 @@ use yaak::plugin_events::{
|
||||
use yaak::response_body::FileResponseBodyStore;
|
||||
use yaak_crypto::manager::EncryptionManager;
|
||||
use yaak_http::cookies::get_cookie_value_from_jar;
|
||||
use yaak_models::models::{HttpResponse, Plugin};
|
||||
use yaak_models::models::{HttpRequest, HttpResponse, Plugin};
|
||||
use yaak_models::queries::any_request::AnyRequest;
|
||||
use yaak_models::util::UpdateSource;
|
||||
use yaak_plugins::error::Error::PluginErr;
|
||||
@@ -111,7 +111,7 @@ async fn handle_host_plugin_request<R: Runtime>(
|
||||
}
|
||||
|
||||
let new_plugin = Plugin { updated_at: Utc::now().naive_utc(), ..plugin };
|
||||
app_handle.db().upsert_plugin(&new_plugin, &UpdateSource::Plugin)?;
|
||||
app_handle.with_tx(|tx| tx.upsert_plugin(&new_plugin, &UpdateSource::Plugin))?;
|
||||
}
|
||||
|
||||
if !req.silent {
|
||||
@@ -280,48 +280,20 @@ async fn handle_host_plugin_request<R: Runtime>(
|
||||
}
|
||||
HostRequest::SendHttpRequest(req) => {
|
||||
let window = get_window_from_plugin_context(app_handle, plugin_context)?;
|
||||
let mut http_request = req.http_request.clone();
|
||||
let workspace =
|
||||
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
|
||||
let cookie_jar = cookie_jar_from_window(&window);
|
||||
let environment = environment_from_window(&window);
|
||||
|
||||
if http_request.workspace_id.is_empty() {
|
||||
http_request.workspace_id = workspace.id;
|
||||
}
|
||||
|
||||
let http_response = if http_request.id.is_empty() {
|
||||
HttpResponse::default()
|
||||
} else {
|
||||
let blobs = window.blob_manager();
|
||||
window.db().upsert_http_response(
|
||||
&HttpResponse {
|
||||
request_id: http_request.id.clone(),
|
||||
workspace_id: http_request.workspace_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
&blobs,
|
||||
)?
|
||||
};
|
||||
|
||||
let http_response = send_http_request_with_context(
|
||||
let sent = send_http_request_in_window(
|
||||
&window,
|
||||
&http_request,
|
||||
&http_response,
|
||||
environment,
|
||||
cookie_jar,
|
||||
&mut tokio::sync::watch::channel(false).1,
|
||||
req.http_request.clone(),
|
||||
req.environment_id.as_deref(),
|
||||
plugin_context,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// An ad-hoc request saves nothing, so the engine hands the body
|
||||
// back and this reply is the only place the plugin can get it.
|
||||
let body = http_response.body.returned_bytes().map(|b| BASE64_STANDARD.encode(b));
|
||||
let body = sent.body.returned_bytes().map(|b| BASE64_STANDARD.encode(b));
|
||||
|
||||
Ok(Some(InternalEventPayload::SendHttpRequestResponse(SendHttpRequestResponse {
|
||||
http_response: http_response.response,
|
||||
http_response: sent.response,
|
||||
body,
|
||||
})))
|
||||
}
|
||||
@@ -462,3 +434,63 @@ async fn handle_host_plugin_request<R: Runtime>(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send on behalf of a plugin or MCP client, from `window`'s workspace and
|
||||
/// with its selected environment unless `environment_id` overrides it.
|
||||
pub(crate) async fn send_http_request_in_window<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
mut http_request: HttpRequest,
|
||||
environment_id: Option<&str>,
|
||||
plugin_context: &yaak_plugins::events::PluginContext,
|
||||
) -> Result<SentHttpRequest> {
|
||||
let workspace =
|
||||
workspace_from_window(window).expect("Failed to get workspace_id from window URL");
|
||||
let cookie_jar = cookie_jar_from_window(window);
|
||||
|
||||
if http_request.workspace_id.is_empty() {
|
||||
http_request.workspace_id = workspace.id.clone();
|
||||
}
|
||||
|
||||
let environment = if let Some(environment_id) = environment_id {
|
||||
if http_request.workspace_id != workspace.id {
|
||||
return Err(crate::error::Error::GenericError(
|
||||
"HTTP request does not belong to the selected workspace".to_string(),
|
||||
));
|
||||
}
|
||||
Some(
|
||||
window
|
||||
.db()
|
||||
.get_environment_for_workspace(&http_request.workspace_id, environment_id)?,
|
||||
)
|
||||
} else {
|
||||
environment_from_window(window)
|
||||
};
|
||||
|
||||
let http_response = if http_request.id.is_empty() {
|
||||
HttpResponse::default()
|
||||
} else {
|
||||
let blobs = window.blob_manager();
|
||||
window.with_tx(|tx| {
|
||||
tx.upsert_http_response(
|
||||
&HttpResponse {
|
||||
request_id: http_request.id.clone(),
|
||||
workspace_id: http_request.workspace_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
&blobs,
|
||||
)
|
||||
})?
|
||||
};
|
||||
|
||||
send_http_request_with_context(
|
||||
window,
|
||||
&http_request,
|
||||
&http_response,
|
||||
environment,
|
||||
cookie_jar,
|
||||
&tokio::sync::watch::channel(false).1,
|
||||
plugin_context,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -16,8 +16,7 @@ use std::time::{Duration, Instant};
|
||||
use tauri::path::BaseDirectory;
|
||||
use tauri::plugin::{Builder, TauriPlugin};
|
||||
use tauri::{
|
||||
AppHandle, Emitter, Manager, RunEvent, Runtime, State, WebviewWindow, WindowEvent,
|
||||
is_dev,
|
||||
AppHandle, Emitter, Manager, RunEvent, Runtime, State, WebviewWindow, WindowEvent, is_dev,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
use ts_rs::TS;
|
||||
@@ -28,10 +27,10 @@ use yaak_plugins::api::{
|
||||
PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse, check_plugin_updates,
|
||||
search_plugins,
|
||||
};
|
||||
use yaak_plugins::error::Error::PluginErr;
|
||||
use yaak_plugins::events::{Color, PluginContext, ShowToastRequest};
|
||||
use yaak_plugins::install::{delete_and_uninstall, download_and_install};
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
use yaak_plugins::error::Error::PluginErr;
|
||||
use yaak_plugins::plugin_meta::get_plugin_meta;
|
||||
|
||||
static EXITING: AtomicBool = AtomicBool::new(false);
|
||||
@@ -203,16 +202,18 @@ pub async fn cmd_plugins_install_from_directory<R: Runtime>(
|
||||
// Resolve the manager before writing the row so startup's plugin snapshot
|
||||
// can't include it and boot it a second time
|
||||
let plugin_manager = Arc::new(plugin_manager(&window).await?);
|
||||
let plugin = window.db().upsert_plugin(
|
||||
&Plugin {
|
||||
directory: directory.into(),
|
||||
url: None,
|
||||
enabled: true,
|
||||
source: PluginSource::Filesystem,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
let plugin = window.with_tx(|tx| {
|
||||
tx.upsert_plugin(
|
||||
&Plugin {
|
||||
directory: directory.into(),
|
||||
url: None,
|
||||
enabled: true,
|
||||
source: PluginSource::Filesystem,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
plugin_manager.add_plugin(&window.plugin_context(), &plugin).await?;
|
||||
|
||||
@@ -355,9 +356,11 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(yaak_plugins::error::Error::PluginErr(
|
||||
"Timed out starting the plugin runtime".to_string(),
|
||||
)));
|
||||
.unwrap_or_else(|_| {
|
||||
Err(yaak_plugins::error::Error::PluginErr(
|
||||
"Timed out starting the plugin runtime".to_string(),
|
||||
))
|
||||
});
|
||||
|
||||
let manager = match result {
|
||||
Ok(manager) => manager,
|
||||
|
||||
@@ -4,5 +4,5 @@
|
||||
//! `yaak-commands` when the template commands did. Callers in this crate do not
|
||||
//! need to track which is which.
|
||||
|
||||
pub use yaak_models::render::{render_grpc_request, render_http_request};
|
||||
pub use yaak_commands::render::{render_json_value, render_template};
|
||||
pub use yaak_models::render::{render_grpc_request, render_http_request};
|
||||
@@ -21,9 +21,9 @@ use crate::notifications::YaakNotifier;
|
||||
use crate::updates::YaakUpdater;
|
||||
use log::warn;
|
||||
use serde::Serialize;
|
||||
use tauri::{Manager, Runtime, State, WebviewWindow};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tauri::{Manager, Runtime, State, WebviewWindow};
|
||||
use tokio::sync::Mutex;
|
||||
use yaak_commands::{Host, PluginHost};
|
||||
use yaak_core::WorkspaceContext;
|
||||
@@ -32,8 +32,8 @@ use yaak_git::{
|
||||
BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote,
|
||||
GitStatusSummary, GitWorktreeStatus, PullResult, PushResult,
|
||||
};
|
||||
use yaak_grpc::manager::GrpcHandle;
|
||||
use yaak_grpc::ServiceDefinition;
|
||||
use yaak_grpc::manager::GrpcHandle;
|
||||
use yaak_models::blob_manager::BlobManager;
|
||||
use yaak_models::models::{
|
||||
GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse,
|
||||
@@ -42,26 +42,26 @@ use yaak_models::models::{
|
||||
};
|
||||
use yaak_models::query_manager::QueryManager;
|
||||
use yaak_models::util::{BatchUpsertResult, ImportPlan};
|
||||
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
|
||||
use yaak_plugins::events::{
|
||||
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
|
||||
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse, ImportResponse,
|
||||
JsonPrimitive, RenderPurpose, GetFolderActionsResponse, GetGrpcRequestActionsResponse,
|
||||
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse,
|
||||
GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse,
|
||||
GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse,
|
||||
GetWorkspaceActionsResponse,
|
||||
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse,
|
||||
GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse,
|
||||
GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse,
|
||||
GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse,
|
||||
GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, ImportResponse, JsonPrimitive,
|
||||
RenderPurpose,
|
||||
};
|
||||
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
use yaak_plugins::native_template_functions::encrypt_secure_template_function;
|
||||
use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||
use yaak_plugins::plugin_meta::PluginMetadata;
|
||||
use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||
use yaak_rpc::RpcRouter;
|
||||
use yaak_rpc_schema::*;
|
||||
use yaak_sse::sse::ServerSentEvent;
|
||||
use yaak_sync::sync::SyncOp;
|
||||
use yaak_templates::TemplateCallback;
|
||||
use yaak_tauri_utils::window::WorkspaceWindowTrait;
|
||||
use yaak_templates::TemplateCallback;
|
||||
use yaak_ws::WebsocketManager;
|
||||
|
||||
/// Per-call context: the window a command was invoked from.
|
||||
@@ -231,17 +231,15 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
|
||||
Ok(self.pm().await?.call_workspace_action(&self.plugin_context(), req).await?)
|
||||
}
|
||||
|
||||
async fn call_folder_action(
|
||||
&self,
|
||||
req: CallFolderActionRequest,
|
||||
) -> yaak_commands::Result<()> {
|
||||
async fn call_folder_action(&self, req: CallFolderActionRequest) -> yaak_commands::Result<()> {
|
||||
Ok(self.pm().await?.call_folder_action(&self.plugin_context(), req).await?)
|
||||
}
|
||||
|
||||
async fn http_authentication_summaries(
|
||||
&self,
|
||||
) -> yaak_commands::Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
||||
let results = self.pm().await?.get_http_authentication_summaries(&self.plugin_context()).await?;
|
||||
let results =
|
||||
self.pm().await?.get_http_authentication_summaries(&self.plugin_context()).await?;
|
||||
Ok(results.into_iter().map(|(_, a)| a).collect())
|
||||
}
|
||||
|
||||
@@ -393,11 +391,25 @@ async fn cmd_metadata<R: Runtime>(ctx: ClientCtx<R>, _req: CmdMetadataReq) -> Re
|
||||
Ok(crate::cmd_metadata(ctx.window.app_handle().clone()).await?)
|
||||
}
|
||||
|
||||
async fn cmd_template_tokens_to_string<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateTokensToStringReq) -> Result<String> {
|
||||
async fn cmd_agent_setup_status<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdAgentSetupStatusReq,
|
||||
) -> Result<AgentSetupStatus> {
|
||||
let home = ctx.window.app_handle().path().home_dir()?;
|
||||
Ok(yaak_commands::agents::agent_setup_status(&home, req.agent))
|
||||
}
|
||||
|
||||
async fn cmd_template_tokens_to_string<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdTemplateTokensToStringReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::templates::cmd_template_tokens_to_string(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_render_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdRenderTemplateReq) -> Result<String> {
|
||||
async fn cmd_render_template<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdRenderTemplateReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::templates::cmd_render_template(ctx, req).await?)
|
||||
}
|
||||
|
||||
@@ -405,72 +417,144 @@ async fn cmd_send_feedback<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendFeedbackRe
|
||||
Ok(crate::cmd_send_feedback(ctx.window.app_handle().clone(), req.feature, req.text).await?)
|
||||
}
|
||||
|
||||
async fn cmd_dismiss_notification<R: Runtime>(ctx: ClientCtx<R>, req: CmdDismissNotificationReq) -> Result<()> {
|
||||
Ok(crate::cmd_dismiss_notification(ctx.window.clone(), &req.notification_id, ctx.window.app_handle().state::<Mutex<YaakNotifier>>()).await?)
|
||||
async fn cmd_dismiss_notification<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDismissNotificationReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::cmd_dismiss_notification(
|
||||
ctx.window.clone(),
|
||||
&req.notification_id,
|
||||
ctx.window.app_handle().state::<Mutex<YaakNotifier>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_grpc_reflect<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcReflectReq) -> Result<Vec<ServiceDefinition>> {
|
||||
Ok(crate::cmd_grpc_reflect(&req.request_id, req.environment_id.as_deref(), req.proto_files, ctx.window.clone(), ctx.window.app_handle().clone(), ctx.window.app_handle().state::<Mutex<GrpcHandle>>()).await?)
|
||||
async fn cmd_grpc_reflect<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGrpcReflectReq,
|
||||
) -> Result<Vec<ServiceDefinition>> {
|
||||
Ok(crate::cmd_grpc_reflect(
|
||||
&req.request_id,
|
||||
req.environment_id.as_deref(),
|
||||
req.proto_files,
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().clone(),
|
||||
ctx.window.app_handle().state::<Mutex<GrpcHandle>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_grpc_go<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcGoReq) -> Result<String> {
|
||||
Ok(crate::cmd_grpc_go(&req.request_id, req.environment_id.as_deref(), req.proto_files, ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<GrpcHandle>>()).await?)
|
||||
Ok(crate::cmd_grpc_go(
|
||||
&req.request_id,
|
||||
req.environment_id.as_deref(),
|
||||
req.proto_files,
|
||||
ctx.window.app_handle().clone(),
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().state::<Mutex<GrpcHandle>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_restart<R: Runtime>(ctx: ClientCtx<R>, _req: CmdRestartReq) -> Result<()> {
|
||||
Ok(crate::cmd_restart(ctx.window.app_handle().clone()).await?)
|
||||
}
|
||||
|
||||
async fn cmd_send_ephemeral_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendEphemeralRequestReq) -> Result<EphemeralHttpResponse> {
|
||||
Ok(crate::cmd_send_ephemeral_request(req.request, req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), ctx.window.clone(), ctx.window.app_handle().clone()).await?)
|
||||
async fn cmd_send_ephemeral_request<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdSendEphemeralRequestReq,
|
||||
) -> Result<EphemeralHttpResponse> {
|
||||
Ok(crate::cmd_send_ephemeral_request(
|
||||
req.request,
|
||||
req.environment_id.as_deref(),
|
||||
req.cookie_jar_id.as_deref(),
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().clone(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_format_json<R: Runtime>(ctx: ClientCtx<R>, req: CmdFormatJsonReq) -> Result<String> {
|
||||
Ok(yaak_commands::data::cmd_format_json(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_format_graphql<R: Runtime>(_ctx: ClientCtx<R>, req: CmdFormatGraphqlReq) -> Result<String> {
|
||||
async fn cmd_format_graphql<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdFormatGraphqlReq,
|
||||
) -> Result<String> {
|
||||
Ok(crate::cmd_format_graphql(&req.text).await?)
|
||||
}
|
||||
|
||||
async fn cmd_http_response_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyReq) -> Result<FilterResponse> {
|
||||
Ok(crate::cmd_http_response_body(ctx.window.clone(), &req.response_id, req.filter.as_deref()).await?)
|
||||
async fn cmd_http_response_body<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdHttpResponseBodyReq,
|
||||
) -> Result<FilterResponse> {
|
||||
Ok(crate::cmd_http_response_body(ctx.window.clone(), &req.response_id, req.filter.as_deref())
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_http_response_body_path<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyPathReq) -> Result<Option<String>> {
|
||||
async fn cmd_http_response_body_path<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdHttpResponseBodyPathReq,
|
||||
) -> Result<Option<String>> {
|
||||
Ok(yaak_commands::responses::cmd_http_response_body_path(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_http_request_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpRequestBodyReq) -> Result<Option<Vec<u8>>> {
|
||||
async fn cmd_http_request_body<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdHttpRequestBodyReq,
|
||||
) -> Result<Option<Vec<u8>>> {
|
||||
Ok(yaak_commands::responses::cmd_http_request_body(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_get_sse_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetSseEventsReq) -> Result<Vec<ServerSentEvent>> {
|
||||
async fn cmd_get_sse_events<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGetSseEventsReq,
|
||||
) -> Result<Vec<ServerSentEvent>> {
|
||||
Ok(crate::cmd_get_sse_events(ctx.window.app_handle().clone(), &req.response_id).await?)
|
||||
}
|
||||
|
||||
async fn cmd_get_http_response_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpResponseEventsReq) -> Result<Vec<HttpResponseEvent>> {
|
||||
async fn cmd_get_http_response_events<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGetHttpResponseEventsReq,
|
||||
) -> Result<Vec<HttpResponseEvent>> {
|
||||
Ok(yaak_commands::responses::cmd_get_http_response_events(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_import_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportDataReq) -> Result<ImportPlan> {
|
||||
Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_path, req.destination).await?)
|
||||
async fn cmd_import_data<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdImportDataReq,
|
||||
) -> Result<ImportPlan> {
|
||||
Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_paths, &req.urls, req.destination)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_import_url<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportUrlReq) -> Result<ImportPlan> {
|
||||
Ok(crate::cmd_import_url(ctx.window.clone(), &req.url, req.destination).await?)
|
||||
}
|
||||
|
||||
async fn cmd_commit_import<R: Runtime>(ctx: ClientCtx<R>, req: CmdCommitImportReq) -> Result<BatchUpsertResult> {
|
||||
async fn cmd_commit_import<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCommitImportReq,
|
||||
) -> Result<BatchUpsertResult> {
|
||||
Ok(crate::cmd_commit_import(ctx.window.clone(), req.plan).await?)
|
||||
}
|
||||
|
||||
async fn cmd_list_import_sources<R: Runtime>(ctx: ClientCtx<R>, req: CmdListImportSourcesReq) -> Result<Vec<ImportSource>> {
|
||||
async fn cmd_list_import_sources<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdListImportSourcesReq,
|
||||
) -> Result<Vec<ImportSource>> {
|
||||
use crate::models_ext::QueryManagerExt;
|
||||
Ok(ctx.window.db().list_import_sources(&req.workspace_id)?)
|
||||
}
|
||||
|
||||
async fn cmd_import_sources_for_origin<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportSourcesForOriginReq) -> Result<Vec<ImportSource>> {
|
||||
async fn cmd_detect_import_source<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDetectImportSourceReq,
|
||||
) -> Result<String> {
|
||||
Ok(crate::import::detect_import_source(&ctx.window, req.file_path, req.url).await?)
|
||||
}
|
||||
|
||||
async fn cmd_import_sources_for_origin<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdImportSourcesForOriginReq,
|
||||
) -> Result<Vec<ImportSource>> {
|
||||
use crate::models_ext::QueryManagerExt;
|
||||
let origin = match (req.file_path, req.url) {
|
||||
(Some(file_path), _) => crate::import::file_origin(&file_path).origin,
|
||||
@@ -483,151 +567,282 @@ async fn cmd_import_sources_for_origin<R: Runtime>(ctx: ClientCtx<R>, req: CmdIm
|
||||
Ok(ctx.window.db().list_import_sources_by_origin(&origin)?)
|
||||
}
|
||||
|
||||
async fn cmd_http_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpRequestActionsReq) -> Result<Vec<GetHttpRequestActionsResponse>> {
|
||||
async fn cmd_http_request_actions<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdHttpRequestActionsReq,
|
||||
) -> Result<Vec<GetHttpRequestActionsResponse>> {
|
||||
Ok(yaak_commands::actions::cmd_http_request_actions(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_websocket_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdWebsocketRequestActionsReq) -> Result<Vec<GetWebsocketRequestActionsResponse>> {
|
||||
async fn cmd_websocket_request_actions<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdWebsocketRequestActionsReq,
|
||||
) -> Result<Vec<GetWebsocketRequestActionsResponse>> {
|
||||
Ok(yaak_commands::actions::cmd_websocket_request_actions(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_call_websocket_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallWebsocketRequestActionReq) -> Result<()> {
|
||||
async fn cmd_call_websocket_request_action<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCallWebsocketRequestActionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::actions::cmd_call_websocket_request_action(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_workspace_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdWorkspaceActionsReq) -> Result<Vec<GetWorkspaceActionsResponse>> {
|
||||
async fn cmd_workspace_actions<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdWorkspaceActionsReq,
|
||||
) -> Result<Vec<GetWorkspaceActionsResponse>> {
|
||||
Ok(yaak_commands::actions::cmd_workspace_actions(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_call_workspace_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallWorkspaceActionReq) -> Result<()> {
|
||||
async fn cmd_call_workspace_action<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCallWorkspaceActionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::actions::cmd_call_workspace_action(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_folder_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdFolderActionsReq) -> Result<Vec<GetFolderActionsResponse>> {
|
||||
async fn cmd_folder_actions<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdFolderActionsReq,
|
||||
) -> Result<Vec<GetFolderActionsResponse>> {
|
||||
Ok(yaak_commands::actions::cmd_folder_actions(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_call_folder_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallFolderActionReq) -> Result<()> {
|
||||
async fn cmd_call_folder_action<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCallFolderActionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::actions::cmd_call_folder_action(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_grpc_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcRequestActionsReq) -> Result<Vec<GetGrpcRequestActionsResponse>> {
|
||||
async fn cmd_grpc_request_actions<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGrpcRequestActionsReq,
|
||||
) -> Result<Vec<GetGrpcRequestActionsResponse>> {
|
||||
Ok(yaak_commands::actions::cmd_grpc_request_actions(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_template_function_summaries<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateFunctionSummariesReq) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
|
||||
async fn cmd_template_function_summaries<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdTemplateFunctionSummariesReq,
|
||||
) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
|
||||
Ok(yaak_commands::templates::cmd_template_function_summaries(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_template_function_config<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateFunctionConfigReq) -> Result<GetTemplateFunctionConfigResponse> {
|
||||
async fn cmd_template_function_config<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdTemplateFunctionConfigReq,
|
||||
) -> Result<GetTemplateFunctionConfigResponse> {
|
||||
Ok(yaak_commands::templates::cmd_template_function_config(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_get_http_authentication_summaries<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpAuthenticationSummariesReq) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
||||
async fn cmd_get_http_authentication_summaries<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGetHttpAuthenticationSummariesReq,
|
||||
) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> {
|
||||
Ok(yaak_commands::auth::cmd_get_http_authentication_summaries(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_get_http_authentication_config<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpAuthenticationConfigReq) -> Result<GetHttpAuthenticationConfigResponse> {
|
||||
async fn cmd_get_http_authentication_config<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGetHttpAuthenticationConfigReq,
|
||||
) -> Result<GetHttpAuthenticationConfigResponse> {
|
||||
Ok(yaak_commands::auth::cmd_get_http_authentication_config(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_call_http_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallHttpRequestActionReq) -> Result<()> {
|
||||
async fn cmd_call_http_request_action<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCallHttpRequestActionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::actions::cmd_call_http_request_action(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_call_grpc_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallGrpcRequestActionReq) -> Result<()> {
|
||||
async fn cmd_call_grpc_request_action<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCallGrpcRequestActionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::actions::cmd_call_grpc_request_action(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_call_http_authentication_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallHttpAuthenticationActionReq) -> Result<()> {
|
||||
async fn cmd_call_http_authentication_action<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCallHttpAuthenticationActionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::auth::cmd_call_http_authentication_action(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_curl_to_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdCurlToRequestReq) -> Result<HttpRequest> {
|
||||
async fn cmd_curl_to_request<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCurlToRequestReq,
|
||||
) -> Result<HttpRequest> {
|
||||
Ok(yaak_commands::actions::cmd_curl_to_request(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_export_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdExportDataReq) -> Result<()> {
|
||||
async fn cmd_export_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdExportDataReq) -> Result<String> {
|
||||
Ok(yaak_commands::data::cmd_export_data(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_save_base64_to_binary<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveBase64ToBinaryReq) -> Result<()> {
|
||||
Ok(crate::cmd_save_base64_to_binary(ctx.window.app_handle().clone(), &req.filepath, &req.data).await?)
|
||||
async fn cmd_create_example_workspace<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdCreateExampleWorkspaceReq,
|
||||
) -> Result<BatchUpsertResult> {
|
||||
Ok(yaak_commands::data::cmd_create_example_workspace(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_save_base64_to_binary<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdSaveBase64ToBinaryReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::cmd_save_base64_to_binary(ctx.window.app_handle().clone(), &req.filepath, &req.data)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_save_response<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveResponseReq) -> Result<()> {
|
||||
Ok(yaak_commands::responses::cmd_save_response(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_send_http_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendHttpRequestReq) -> Result<HttpResponse> {
|
||||
Ok(crate::cmd_send_http_request(ctx.window.app_handle().clone(), ctx.window.clone(), req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), req.request_id).await?)
|
||||
async fn cmd_send_http_request<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdSendHttpRequestReq,
|
||||
) -> Result<HttpResponse> {
|
||||
Ok(crate::cmd_send_http_request(
|
||||
ctx.window.app_handle().clone(),
|
||||
ctx.window.clone(),
|
||||
req.environment_id.as_deref(),
|
||||
req.cookie_jar_id.as_deref(),
|
||||
req.request_id,
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_reload_plugins<R: Runtime>(ctx: ClientCtx<R>, req: CmdReloadPluginsReq) -> Result<Vec<(String, String)>> {
|
||||
async fn cmd_reload_plugins<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdReloadPluginsReq,
|
||||
) -> Result<Vec<(String, String)>> {
|
||||
Ok(yaak_commands::actions::cmd_reload_plugins(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugin_info<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginInfoReq) -> Result<PluginMetadata> {
|
||||
async fn cmd_plugin_info<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdPluginInfoReq,
|
||||
) -> Result<PluginMetadata> {
|
||||
Ok(yaak_commands::plugins::cmd_plugin_info(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_delete_all_grpc_connections<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteAllGrpcConnectionsReq) -> Result<()> {
|
||||
async fn cmd_delete_all_grpc_connections<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDeleteAllGrpcConnectionsReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::models::cmd_delete_all_grpc_connections(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_delete_send_history<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteSendHistoryReq) -> Result<()> {
|
||||
async fn cmd_delete_send_history<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDeleteSendHistoryReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::models::cmd_delete_send_history(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_delete_all_http_responses<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteAllHttpResponsesReq) -> Result<()> {
|
||||
async fn cmd_delete_all_http_responses<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDeleteAllHttpResponsesReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::models::cmd_delete_all_http_responses(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_get_workspace_meta<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetWorkspaceMetaReq) -> Result<WorkspaceMeta> {
|
||||
async fn cmd_get_workspace_meta<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGetWorkspaceMetaReq,
|
||||
) -> Result<WorkspaceMeta> {
|
||||
Ok(yaak_commands::models::cmd_get_workspace_meta(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_new_child_window<R: Runtime>(ctx: ClientCtx<R>, req: CmdNewChildWindowReq) -> Result<()> {
|
||||
Ok(crate::cmd_new_child_window(ctx.window.clone(), &req.url, &req.label, &req.title, req.inner_size).await?)
|
||||
async fn cmd_new_child_window<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdNewChildWindowReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::cmd_new_child_window(
|
||||
ctx.window.clone(),
|
||||
&req.url,
|
||||
&req.label,
|
||||
&req.title,
|
||||
req.inner_size,
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_new_main_window<R: Runtime>(ctx: ClientCtx<R>, req: CmdNewMainWindowReq) -> Result<()> {
|
||||
async fn cmd_new_main_window<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdNewMainWindowReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::cmd_new_main_window(ctx.window.app_handle().clone(), &req.url).await?)
|
||||
}
|
||||
|
||||
async fn cmd_check_for_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdCheckForUpdatesReq) -> Result<bool> {
|
||||
Ok(crate::cmd_check_for_updates(ctx.window.clone(), ctx.window.app_handle().state::<Mutex<YaakUpdater>>()).await?)
|
||||
async fn cmd_check_for_updates<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
_req: CmdCheckForUpdatesReq,
|
||||
) -> Result<bool> {
|
||||
Ok(crate::cmd_check_for_updates(
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().state::<Mutex<YaakUpdater>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_decrypt_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdDecryptTemplateReq) -> Result<String> {
|
||||
async fn cmd_decrypt_template<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDecryptTemplateReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::encryption::cmd_decrypt_template(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_secure_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdSecureTemplateReq) -> Result<String> {
|
||||
async fn cmd_secure_template<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdSecureTemplateReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::encryption::cmd_secure_template(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_get_themes<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetThemesReq) -> Result<Vec<GetThemesResponse>> {
|
||||
async fn cmd_get_themes<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdGetThemesReq,
|
||||
) -> Result<Vec<GetThemesResponse>> {
|
||||
Ok(yaak_commands::templates::cmd_get_themes(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_enable_encryption<R: Runtime>(ctx: ClientCtx<R>, req: CmdEnableEncryptionReq) -> Result<()> {
|
||||
async fn cmd_enable_encryption<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdEnableEncryptionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::encryption::cmd_enable_encryption(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_reveal_workspace_key<R: Runtime>(ctx: ClientCtx<R>, req: CmdRevealWorkspaceKeyReq) -> Result<String> {
|
||||
async fn cmd_reveal_workspace_key<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdRevealWorkspaceKeyReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::encryption::cmd_reveal_workspace_key(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_set_workspace_key<R: Runtime>(ctx: ClientCtx<R>, req: CmdSetWorkspaceKeyReq) -> Result<()> {
|
||||
async fn cmd_set_workspace_key<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdSetWorkspaceKeyReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::encryption::cmd_set_workspace_key(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_disable_encryption<R: Runtime>(ctx: ClientCtx<R>, req: CmdDisableEncryptionReq) -> Result<()> {
|
||||
async fn cmd_disable_encryption<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDisableEncryptionReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::encryption::cmd_disable_encryption(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_default_headers<R: Runtime>(ctx: ClientCtx<R>, req: CmdDefaultHeadersReq) -> Result<Vec<HttpRequestHeader>> {
|
||||
async fn cmd_default_headers<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdDefaultHeadersReq,
|
||||
) -> Result<Vec<HttpRequestHeader>> {
|
||||
Ok(yaak_commands::models::cmd_default_headers(ctx, req).await?)
|
||||
}
|
||||
|
||||
@@ -649,39 +864,66 @@ async fn models_delete<R: Runtime>(ctx: ClientCtx<R>, req: ModelsDeleteReq) -> R
|
||||
Ok(deleted?)
|
||||
}
|
||||
|
||||
async fn models_duplicate<R: Runtime>(ctx: ClientCtx<R>, req: ModelsDuplicateReq) -> Result<String> {
|
||||
async fn models_duplicate<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsDuplicateReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::models::models_duplicate(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_snapshot_request<R: Runtime>(ctx: ClientCtx<R>, req: ModelsSnapshotRequestReq) -> Result<ModelVersion> {
|
||||
async fn models_snapshot_request<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsSnapshotRequestReq,
|
||||
) -> Result<ModelVersion> {
|
||||
Ok(yaak_commands::models::models_snapshot_request(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_request_version<R: Runtime>(ctx: ClientCtx<R>, req: ModelsRequestVersionReq) -> Result<RequestVersionComparison> {
|
||||
async fn models_request_version<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsRequestVersionReq,
|
||||
) -> Result<RequestVersionComparison> {
|
||||
Ok(yaak_commands::models::models_request_version(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_restore_request_version<R: Runtime>(ctx: ClientCtx<R>, req: ModelsRestoreRequestVersionReq) -> Result<String> {
|
||||
async fn models_restore_request_version<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsRestoreRequestVersionReq,
|
||||
) -> Result<String> {
|
||||
Ok(yaak_commands::models::models_restore_request_version(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_websocket_events<R: Runtime>(ctx: ClientCtx<R>, req: ModelsWebsocketEventsReq) -> Result<Vec<WebsocketEvent>> {
|
||||
async fn models_websocket_events<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsWebsocketEventsReq,
|
||||
) -> Result<Vec<WebsocketEvent>> {
|
||||
Ok(yaak_commands::models::models_websocket_events(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_grpc_events<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGrpcEventsReq) -> Result<Vec<GrpcEvent>> {
|
||||
async fn models_grpc_events<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsGrpcEventsReq,
|
||||
) -> Result<Vec<GrpcEvent>> {
|
||||
Ok(yaak_commands::models::models_grpc_events(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_get_settings<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGetSettingsReq) -> Result<Settings> {
|
||||
async fn models_get_settings<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsGetSettingsReq,
|
||||
) -> Result<Settings> {
|
||||
Ok(yaak_commands::models::models_get_settings(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_get_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGetGraphqlIntrospectionReq) -> Result<Option<GraphQlIntrospection>> {
|
||||
async fn models_get_graphql_introspection<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsGetGraphqlIntrospectionReq,
|
||||
) -> Result<Option<GraphQlIntrospection>> {
|
||||
Ok(yaak_commands::models::models_get_graphql_introspection(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn models_upsert_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req: ModelsUpsertGraphqlIntrospectionReq) -> Result<GraphQlIntrospection> {
|
||||
async fn models_upsert_graphql_introspection<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsUpsertGraphqlIntrospectionReq,
|
||||
) -> Result<GraphQlIntrospection> {
|
||||
Ok(yaak_commands::models::models_upsert_graphql_introspection(ctx, req).await?)
|
||||
}
|
||||
|
||||
@@ -692,7 +934,10 @@ async fn models_upsert_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req:
|
||||
/// freezes the app"). Escape sequences sidestep it. This is a quirk of the
|
||||
/// webview transport, not of the data, so it lives in the adapter rather than
|
||||
/// the shared handler.
|
||||
async fn models_workspace_models<R: Runtime>(ctx: ClientCtx<R>, req: ModelsWorkspaceModelsReq) -> Result<String> {
|
||||
async fn models_workspace_models<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: ModelsWorkspaceModelsReq,
|
||||
) -> Result<String> {
|
||||
let json = yaak_commands::models::models_workspace_models(ctx, req).await?;
|
||||
Ok(escape_str_for_webview(&json))
|
||||
}
|
||||
@@ -718,7 +963,10 @@ fn escape_str_for_webview(input: &str) -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn cmd_git_checkout<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitCheckoutReq) -> Result<String> {
|
||||
async fn cmd_git_checkout<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitCheckoutReq,
|
||||
) -> Result<String> {
|
||||
Ok(crate::git_ext::cmd_git_checkout(&req.dir, &req.branch, req.force).await?)
|
||||
}
|
||||
|
||||
@@ -726,31 +974,52 @@ async fn cmd_git_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitBranchReq) ->
|
||||
Ok(crate::git_ext::cmd_git_branch(&req.dir, &req.branch, req.base.as_deref()).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_delete_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitDeleteBranchReq) -> Result<BranchDeleteResult> {
|
||||
async fn cmd_git_delete_branch<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitDeleteBranchReq,
|
||||
) -> Result<BranchDeleteResult> {
|
||||
Ok(crate::git_ext::cmd_git_delete_branch(&req.dir, &req.branch, req.force).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_delete_remote_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitDeleteRemoteBranchReq) -> Result<()> {
|
||||
async fn cmd_git_delete_remote_branch<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitDeleteRemoteBranchReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_delete_remote_branch(&req.dir, &req.branch).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_merge_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitMergeBranchReq) -> Result<()> {
|
||||
async fn cmd_git_merge_branch<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitMergeBranchReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_merge_branch(&req.dir, &req.branch).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_rename_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRenameBranchReq) -> Result<()> {
|
||||
async fn cmd_git_rename_branch<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitRenameBranchReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_rename_branch(&req.dir, &req.old_name, &req.new_name).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_status<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitStatusReq) -> Result<GitStatusSummary> {
|
||||
async fn cmd_git_status<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitStatusReq,
|
||||
) -> Result<GitStatusSummary> {
|
||||
Ok(crate::git_ext::cmd_git_status(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_branch_info<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitBranchInfoReq) -> Result<GitBranchInfo> {
|
||||
async fn cmd_git_branch_info<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitBranchInfoReq,
|
||||
) -> Result<GitBranchInfo> {
|
||||
Ok(crate::git_ext::cmd_git_branch_info(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_worktree_status<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitWorktreeStatusReq) -> Result<GitWorktreeStatus> {
|
||||
async fn cmd_git_worktree_status<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitWorktreeStatusReq,
|
||||
) -> Result<GitWorktreeStatus> {
|
||||
Ok(crate::git_ext::cmd_git_worktree_status(&req.dir).await?)
|
||||
}
|
||||
|
||||
@@ -758,15 +1027,25 @@ async fn cmd_git_log<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitLogReq) -> Resul
|
||||
Ok(crate::git_ext::cmd_git_log(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_log_for_file<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitLogForFileReq) -> Result<Vec<GitCommit>> {
|
||||
async fn cmd_git_log_for_file<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitLogForFileReq,
|
||||
) -> Result<Vec<GitCommit>> {
|
||||
Ok(crate::git_ext::cmd_git_log_for_file(&req.dir, req.rela_path).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_file_diff_for_commit<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitFileDiffForCommitReq) -> Result<GitFileDiff> {
|
||||
Ok(crate::git_ext::cmd_git_file_diff_for_commit(&req.dir, &req.commit_oid, req.rela_path).await?)
|
||||
async fn cmd_git_file_diff_for_commit<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitFileDiffForCommitReq,
|
||||
) -> Result<GitFileDiff> {
|
||||
Ok(crate::git_ext::cmd_git_file_diff_for_commit(&req.dir, &req.commit_oid, req.rela_path)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_initialize<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitInitializeReq) -> Result<()> {
|
||||
async fn cmd_git_initialize<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitInitializeReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_initialize(&req.dir).await?)
|
||||
}
|
||||
|
||||
@@ -790,11 +1069,17 @@ async fn cmd_git_pull<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullReq) -> Res
|
||||
Ok(crate::git_ext::cmd_git_pull(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_pull_force_reset<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullForceResetReq) -> Result<PullResult> {
|
||||
async fn cmd_git_pull_force_reset<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitPullForceResetReq,
|
||||
) -> Result<PullResult> {
|
||||
Ok(crate::git_ext::cmd_git_pull_force_reset(&req.dir, &req.remote, &req.branch).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_pull_merge<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullMergeReq) -> Result<PullResult> {
|
||||
async fn cmd_git_pull_merge<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitPullMergeReq,
|
||||
) -> Result<PullResult> {
|
||||
Ok(crate::git_ext::cmd_git_pull_merge(&req.dir, &req.remote, &req.branch).await?)
|
||||
}
|
||||
|
||||
@@ -806,27 +1091,47 @@ async fn cmd_git_unstage<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitUnstageReq)
|
||||
Ok(crate::git_ext::cmd_git_unstage(&req.dir, req.rela_paths).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_reset_changes<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitResetChangesReq) -> Result<()> {
|
||||
async fn cmd_git_reset_changes<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitResetChangesReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_reset_changes(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_restore_files<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRestoreFilesReq) -> Result<()> {
|
||||
async fn cmd_git_restore_files<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitRestoreFilesReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_restore_files(&req.dir, req.rela_paths).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_restore_file_from_commit<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRestoreFileFromCommitReq) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_restore_file_from_commit(&req.dir, &req.commit_oid, req.rela_path).await?)
|
||||
async fn cmd_git_restore_file_from_commit<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitRestoreFileFromCommitReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_restore_file_from_commit(&req.dir, &req.commit_oid, req.rela_path)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_add_credential<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitAddCredentialReq) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_add_credential(&req.remote_url, &req.username, &req.password).await?)
|
||||
async fn cmd_git_add_credential<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitAddCredentialReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::git_ext::cmd_git_add_credential(&req.remote_url, &req.username, &req.password)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_remotes<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRemotesReq) -> Result<Vec<GitRemote>> {
|
||||
async fn cmd_git_remotes<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitRemotesReq,
|
||||
) -> Result<Vec<GitRemote>> {
|
||||
Ok(crate::git_ext::cmd_git_remotes(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_git_add_remote<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitAddRemoteReq) -> Result<GitRemote> {
|
||||
async fn cmd_git_add_remote<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdGitAddRemoteReq,
|
||||
) -> Result<GitRemote> {
|
||||
Ok(crate::git_ext::cmd_git_add_remote(&req.dir, &req.name, &req.url).await?)
|
||||
}
|
||||
|
||||
@@ -834,58 +1139,131 @@ async fn cmd_git_rm_remote<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRmRemoteRe
|
||||
Ok(crate::git_ext::cmd_git_rm_remote(&req.dir, &req.name).await?)
|
||||
}
|
||||
|
||||
async fn cmd_sync_calculate<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncCalculateReq) -> Result<Vec<SyncOp>> {
|
||||
Ok(crate::sync_ext::cmd_sync_calculate(ctx.window.app_handle().clone(), &req.workspace_id, &req.sync_dir).await?)
|
||||
async fn cmd_sync_calculate<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdSyncCalculateReq,
|
||||
) -> Result<Vec<SyncOp>> {
|
||||
Ok(crate::sync_ext::cmd_sync_calculate(
|
||||
ctx.window.app_handle().clone(),
|
||||
&req.workspace_id,
|
||||
&req.sync_dir,
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_sync_calculate_fs<R: Runtime>(_ctx: ClientCtx<R>, req: CmdSyncCalculateFsReq) -> Result<Vec<SyncOp>> {
|
||||
async fn cmd_sync_calculate_fs<R: Runtime>(
|
||||
_ctx: ClientCtx<R>,
|
||||
req: CmdSyncCalculateFsReq,
|
||||
) -> Result<Vec<SyncOp>> {
|
||||
Ok(crate::sync_ext::cmd_sync_calculate_fs(&req.dir).await?)
|
||||
}
|
||||
|
||||
async fn cmd_sync_apply<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncApplyReq) -> Result<()> {
|
||||
Ok(crate::sync_ext::cmd_sync_apply(ctx.window.app_handle().clone(), req.sync_ops, &req.sync_dir, &req.workspace_id).await?)
|
||||
async fn cmd_sync_apply<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncApplyReq) -> Result<bool> {
|
||||
Ok(crate::sync_ext::cmd_sync_apply(
|
||||
ctx.window.app_handle().clone(),
|
||||
req.sync_ops,
|
||||
&req.sync_dir,
|
||||
&req.workspace_id,
|
||||
req.fs_only,
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_ws_delete_connections<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsDeleteConnectionsReq) -> Result<()> {
|
||||
async fn cmd_ws_delete_connections<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdWsDeleteConnectionsReq,
|
||||
) -> Result<()> {
|
||||
Ok(yaak_commands::models::cmd_ws_delete_connections(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_ws_send<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsSendReq) -> Result<WebsocketConnection> {
|
||||
Ok(crate::ws_ext::cmd_ws_send(&req.connection_id, req.environment_id.as_deref(), ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?)
|
||||
async fn cmd_ws_send<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdWsSendReq,
|
||||
) -> Result<WebsocketConnection> {
|
||||
Ok(crate::ws_ext::cmd_ws_send(
|
||||
&req.connection_id,
|
||||
req.environment_id.as_deref(),
|
||||
ctx.window.app_handle().clone(),
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_ws_close<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsCloseReq) -> Result<WebsocketConnection> {
|
||||
Ok(crate::ws_ext::cmd_ws_close(&req.connection_id, ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?)
|
||||
async fn cmd_ws_close<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdWsCloseReq,
|
||||
) -> Result<WebsocketConnection> {
|
||||
Ok(crate::ws_ext::cmd_ws_close(
|
||||
&req.connection_id,
|
||||
ctx.window.app_handle().clone(),
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_ws_connect<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsConnectReq) -> Result<WebsocketConnection> {
|
||||
Ok(crate::ws_ext::cmd_ws_connect(&req.request_id, req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?)
|
||||
async fn cmd_ws_connect<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdWsConnectReq,
|
||||
) -> Result<WebsocketConnection> {
|
||||
Ok(crate::ws_ext::cmd_ws_connect(
|
||||
&req.request_id,
|
||||
req.environment_id.as_deref(),
|
||||
req.cookie_jar_id.as_deref(),
|
||||
ctx.window.app_handle().clone(),
|
||||
ctx.window.clone(),
|
||||
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugins_search<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsSearchReq) -> Result<PluginSearchResponse> {
|
||||
async fn cmd_plugins_search<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdPluginsSearchReq,
|
||||
) -> Result<PluginSearchResponse> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_search(ctx.window.app_handle().clone(), &req.query).await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugins_install<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsInstallReq) -> Result<()> {
|
||||
async fn cmd_plugins_install<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdPluginsInstallReq,
|
||||
) -> Result<()> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_install(ctx.window.clone(), &req.name, req.version).await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugins_install_from_directory<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsInstallFromDirectoryReq) -> Result<Plugin> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_install_from_directory(ctx.window.clone(), &req.directory).await?)
|
||||
async fn cmd_plugins_install_from_directory<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdPluginsInstallFromDirectoryReq,
|
||||
) -> Result<Plugin> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_install_from_directory(ctx.window.clone(), &req.directory)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugins_uninstall<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsUninstallReq) -> Result<Plugin> {
|
||||
async fn cmd_plugins_uninstall<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdPluginsUninstallReq,
|
||||
) -> Result<Plugin> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_uninstall(&req.plugin_id, ctx.window.clone()).await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugin_init_errors<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginInitErrorsReq) -> Result<Vec<(String, String)>> {
|
||||
async fn cmd_plugin_init_errors<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
req: CmdPluginInitErrorsReq,
|
||||
) -> Result<Vec<(String, String)>> {
|
||||
Ok(yaak_commands::plugins::cmd_plugin_init_errors(ctx, req).await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugins_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpdatesReq) -> Result<PluginUpdatesResponse> {
|
||||
async fn cmd_plugins_updates<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
_req: CmdPluginsUpdatesReq,
|
||||
) -> Result<PluginUpdatesResponse> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_updates(ctx.window.app_handle().clone()).await?)
|
||||
}
|
||||
|
||||
async fn cmd_plugins_update_all<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpdateAllReq) -> Result<Vec<PluginNameVersion>> {
|
||||
async fn cmd_plugins_update_all<R: Runtime>(
|
||||
ctx: ClientCtx<R>,
|
||||
_req: CmdPluginsUpdateAllReq,
|
||||
) -> Result<Vec<PluginNameVersion>> {
|
||||
Ok(crate::plugins_ext::cmd_plugins_update_all(ctx.window.clone()).await?)
|
||||
}
|
||||
@@ -12,8 +12,8 @@ use tokio::sync::watch;
|
||||
use yaak_rpc_schema::WatchResult;
|
||||
use yaak_sync::error::Error::InvalidSyncDirectory;
|
||||
use yaak_sync::sync::{
|
||||
FsCandidate, SyncOp, apply_sync_ops, apply_sync_state_ops, compute_sync_ops, get_db_candidates,
|
||||
get_fs_candidates,
|
||||
FsCandidate, SyncOp, apply_db_sync_ops, apply_fs_sync_ops, apply_sync_ops,
|
||||
apply_sync_state_ops, compute_sync_ops, get_db_candidates, get_fs_candidates,
|
||||
};
|
||||
use yaak_sync::watch::{WatchEvent, watch_directory};
|
||||
|
||||
@@ -29,7 +29,7 @@ pub(crate) async fn cmd_sync_calculate<R: Runtime>(
|
||||
let db = app_handle.db();
|
||||
let version = app_handle.package_info().version.to_string();
|
||||
let db_candidates = get_db_candidates(&db, &version, workspace_id, sync_dir)?;
|
||||
let fs_candidates = get_fs_candidates(sync_dir)?
|
||||
let fs_candidates = get_fs_candidates(sync_dir, &db_candidates)?
|
||||
.into_iter()
|
||||
// Only keep items in the same workspace
|
||||
.filter(|fs| fs.model.workspace_id() == workspace_id)
|
||||
@@ -39,7 +39,7 @@ pub(crate) async fn cmd_sync_calculate<R: Runtime>(
|
||||
|
||||
pub(crate) async fn cmd_sync_calculate_fs(dir: &Path) -> Result<Vec<SyncOp>> {
|
||||
let db_candidates = Vec::new();
|
||||
let fs_candidates = get_fs_candidates(dir)?;
|
||||
let fs_candidates = get_fs_candidates(dir, &db_candidates)?;
|
||||
Ok(compute_sync_ops(db_candidates, fs_candidates))
|
||||
}
|
||||
|
||||
@@ -48,12 +48,29 @@ pub(crate) async fn cmd_sync_apply<R: Runtime>(
|
||||
sync_ops: Vec<SyncOp>,
|
||||
sync_dir: &Path,
|
||||
workspace_id: &str,
|
||||
) -> Result<()> {
|
||||
let db = app_handle.db();
|
||||
fs_only: bool,
|
||||
) -> Result<bool> {
|
||||
let blobs = app_handle.blob_manager();
|
||||
let sync_state_ops = apply_sync_ops(&db, &blobs, workspace_id, sync_dir, sync_ops)?;
|
||||
apply_sync_state_ops(&db, workspace_id, sync_dir, sync_state_ops)?;
|
||||
Ok(())
|
||||
if !fs_only || sync_ops.iter().any(|op| !matches!(op, SyncOp::DbCreate { .. })) {
|
||||
let version = app_handle.package_info().version.to_string();
|
||||
return Ok(apply_sync_ops(
|
||||
&app_handle.db_manager(),
|
||||
&blobs,
|
||||
&version,
|
||||
workspace_id,
|
||||
sync_dir,
|
||||
sync_ops,
|
||||
)?);
|
||||
}
|
||||
|
||||
// Opening a sync directory imports its files without existing DB sync state.
|
||||
// Files first, so the write transaction never waits on the filesystem
|
||||
let pending = apply_fs_sync_ops(workspace_id, sync_dir, sync_ops)?;
|
||||
app_handle.db_manager().with_tx(|tx| {
|
||||
let sync_state_ops = apply_db_sync_ops(tx, &blobs, workspace_id, sync_dir, pending)?;
|
||||
apply_sync_state_ops(tx, workspace_id, sync_dir, sync_state_ops)?;
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn sync_watch<R, F>(
|
||||
|
||||
@@ -3,16 +3,26 @@ use crate::error::Result;
|
||||
use crate::import::{file_origin, import_data, url_origin};
|
||||
use crate::models_ext::QueryManagerExt;
|
||||
use log::{info, warn};
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Emitter, Manager, Runtime, Url};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||
use ts_rs::TS;
|
||||
use yaak_api::{ApiClientKind, yaak_api_client};
|
||||
use yaak_models::util::generate_id;
|
||||
use yaak_plugins::events::{Color, ShowToastRequest};
|
||||
use yaak_plugins::install::download_and_install;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "index.ts")]
|
||||
pub struct NavigateWorkspace {
|
||||
workspace_id: String,
|
||||
environment_id: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_deep_link<R: Runtime>(
|
||||
app_handle: &AppHandle<R>,
|
||||
url: &Url,
|
||||
@@ -129,6 +139,15 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
|
||||
timeout: Some(5000),
|
||||
},
|
||||
)?;
|
||||
if let Some(workspace) = results.workspaces.first() {
|
||||
window.emit(
|
||||
"navigate_workspace",
|
||||
NavigateWorkspace {
|
||||
workspace_id: workspace.id.clone(),
|
||||
environment_id: results.environments.first().map(|e| e.id.clone()),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
warn!("Unknown deep link command: {command}");
|
||||
|
||||
@@ -165,6 +165,8 @@ pub fn app_menu<R: Runtime>(app_handle: &AppHandle<R>) -> tauri::Result<Menu<R>>
|
||||
"Generate Theme CSS",
|
||||
)
|
||||
.build(app_handle)?,
|
||||
&MenuItemBuilder::with_id("dev.show_home".to_string(), "Show Home Screen")
|
||||
.build(app_handle)?,
|
||||
],
|
||||
)?,
|
||||
],
|
||||
|
||||
@@ -13,6 +13,7 @@ use tauri::{AppHandle, Manager, Runtime, State, WebviewWindow};
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use url::Url;
|
||||
use yaak_commands::resolve::resolve_websocket_request;
|
||||
use yaak_crypto::manager::EncryptionManager;
|
||||
use yaak_http::cookies::CookieStore;
|
||||
use yaak_http::path_placeholders::apply_path_placeholders;
|
||||
@@ -27,7 +28,6 @@ use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||
use yaak_templates::strip_json_comments::maybe_strip_json_comments;
|
||||
use yaak_templates::{RenderErrorBehavior, RenderOptions};
|
||||
use yaak_tls::find_client_certificate;
|
||||
use yaak_commands::resolve::resolve_websocket_request;
|
||||
use yaak_ws::{WebsocketManager, render_websocket_request};
|
||||
|
||||
pub async fn cmd_ws_send<R: Runtime>(
|
||||
@@ -44,18 +44,20 @@ pub async fn cmd_ws_send<R: Runtime>(
|
||||
{
|
||||
Ok(connection) => Ok(connection),
|
||||
Err(e) => {
|
||||
app_handle.db().upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection.id.clone(),
|
||||
request_id: connection.request_id.clone(),
|
||||
workspace_id: connection.workspace_id.clone(),
|
||||
is_server: false,
|
||||
message_type: WebsocketEventType::Error,
|
||||
message: e.to_string().into(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection.id.clone(),
|
||||
request_id: connection.request_id.clone(),
|
||||
workspace_id: connection.workspace_id.clone(),
|
||||
is_server: false,
|
||||
message_type: WebsocketEventType::Error,
|
||||
message: e.to_string().into(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(connection)
|
||||
}
|
||||
@@ -97,18 +99,20 @@ async fn send_websocket_message<R: Runtime>(
|
||||
let mut ws_manager = ws_manager.lock().await;
|
||||
ws_manager.send(&connection.id, Message::Text(message.clone().into())).await?;
|
||||
|
||||
app_handle.db().upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection.id.clone(),
|
||||
request_id: request.id.clone(),
|
||||
workspace_id: connection.workspace_id.clone(),
|
||||
is_server: false,
|
||||
message_type: WebsocketEventType::Text,
|
||||
message: message.into(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection.id.clone(),
|
||||
request_id: request.id.clone(),
|
||||
workspace_id: connection.workspace_id.clone(),
|
||||
is_server: false,
|
||||
message_type: WebsocketEventType::Text,
|
||||
message: message.into(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(connection.clone())
|
||||
}
|
||||
@@ -119,14 +123,13 @@ pub async fn cmd_ws_close<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
ws_manager: State<'_, Mutex<WebsocketManager>>,
|
||||
) -> Result<WebsocketConnection> {
|
||||
let connection = {
|
||||
let db = app_handle.db();
|
||||
let connection = db.get_websocket_connection(connection_id)?;
|
||||
db.upsert_websocket_connection(
|
||||
let connection = app_handle.with_tx(|tx| {
|
||||
let connection = tx.get_websocket_connection(connection_id)?;
|
||||
tx.upsert_websocket_connection(
|
||||
&WebsocketConnection { state: WebsocketConnectionState::Closing, ..connection },
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?
|
||||
};
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut ws_manager = ws_manager.lock().await;
|
||||
if let Err(e) = ws_manager.close(&connection.id).await {
|
||||
@@ -170,21 +173,22 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Capture the stored request, not the rendered one: what a restore should
|
||||
// put back is what the user typed
|
||||
let version_id = app_handle
|
||||
.db()
|
||||
.snapshot_request_for_send(&AnyRequest::WebsocketRequest(unrendered_request.clone()));
|
||||
|
||||
let connection = app_handle.db().upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
request_id: request_id.to_string(),
|
||||
version_id,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
let connection = app_handle.with_tx(|tx| {
|
||||
// Capture the stored request, not the rendered one: what a restore should
|
||||
// put back is what the user typed
|
||||
let version_id = tx.snapshot_request_for_send(&AnyRequest::WebsocketRequest(
|
||||
unrendered_request.clone(),
|
||||
));
|
||||
tx.upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
request_id: request_id.to_string(),
|
||||
version_id,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let (mut url, url_parameters) = apply_path_placeholders(&request.url, &request.url_parameters);
|
||||
if !url.starts_with("ws://") && !url.starts_with("wss://") {
|
||||
@@ -195,14 +199,16 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
||||
let mut url = match Url::parse(&url) {
|
||||
Ok(url) => url,
|
||||
Err(e) => {
|
||||
return Ok(app_handle.db().upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
error: Some(format!("Failed to parse URL {}", e.to_string())),
|
||||
state: WebsocketConnectionState::Closed,
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?);
|
||||
return Ok(app_handle.with_tx(|tx| {
|
||||
tx.upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
error: Some(format!("Failed to parse URL {}", e.to_string())),
|
||||
state: WebsocketConnectionState::Closed,
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -329,28 +335,32 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return Ok(app_handle.db().upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
error: Some(e.to_string()),
|
||||
state: WebsocketConnectionState::Closed,
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?);
|
||||
return Ok(app_handle.with_tx(|tx| {
|
||||
tx.upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
error: Some(e.to_string()),
|
||||
state: WebsocketConnectionState::Closed,
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?);
|
||||
}
|
||||
};
|
||||
|
||||
app_handle.db().upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection.id.clone(),
|
||||
request_id: request.id.clone(),
|
||||
workspace_id: connection.workspace_id.clone(),
|
||||
is_server: false,
|
||||
message_type: WebsocketEventType::Open,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection.id.clone(),
|
||||
request_id: request.id.clone(),
|
||||
workspace_id: connection.workspace_id.clone(),
|
||||
is_server: false,
|
||||
message_type: WebsocketEventType::Open,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let response_headers = response
|
||||
.headers()
|
||||
@@ -374,20 +384,22 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
||||
if !set_cookie_headers.is_empty() {
|
||||
store.store_cookies_from_response(&convert_ws_url_to_http(&url), &set_cookie_headers);
|
||||
cookie_jar.cookies = store.get_all_cookies();
|
||||
app_handle.db().upsert_cookie_jar(cookie_jar, &UpdateSource::Background)?;
|
||||
app_handle.with_tx(|tx| tx.upsert_cookie_jar(cookie_jar, &UpdateSource::Background))?;
|
||||
}
|
||||
}
|
||||
|
||||
let connection = app_handle.db().upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
state: WebsocketConnectionState::Connected,
|
||||
headers: response_headers,
|
||||
status: response.status().as_u16() as i32,
|
||||
url: request.url.clone(),
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
let connection = app_handle.with_tx(|tx| {
|
||||
tx.upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
state: WebsocketConnectionState::Connected,
|
||||
headers: response_headers,
|
||||
status: response.status().as_u16() as i32,
|
||||
url: request.url.clone(),
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
{
|
||||
let connection_id = connection.id.clone();
|
||||
@@ -403,57 +415,60 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
||||
}
|
||||
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection_id.clone(),
|
||||
request_id: request_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
is_server: true,
|
||||
message_type: match message {
|
||||
Message::Text(_) => WebsocketEventType::Text,
|
||||
Message::Binary(_) => WebsocketEventType::Binary,
|
||||
Message::Ping(_) => WebsocketEventType::Ping,
|
||||
Message::Pong(_) => WebsocketEventType::Pong,
|
||||
Message::Close(_) => WebsocketEventType::Close,
|
||||
// Raw frame will never happen during a read
|
||||
Message::Frame(_) => WebsocketEventType::Frame,
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection_id.clone(),
|
||||
request_id: request_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
is_server: true,
|
||||
message_type: match message {
|
||||
Message::Text(_) => WebsocketEventType::Text,
|
||||
Message::Binary(_) => WebsocketEventType::Binary,
|
||||
Message::Ping(_) => WebsocketEventType::Ping,
|
||||
Message::Pong(_) => WebsocketEventType::Pong,
|
||||
Message::Close(_) => WebsocketEventType::Close,
|
||||
// Raw frame will never happen during a read
|
||||
Message::Frame(_) => WebsocketEventType::Frame,
|
||||
},
|
||||
message: message.into_data().into(),
|
||||
..Default::default()
|
||||
},
|
||||
message: message.into_data().into(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
info!("Websocket connection closed");
|
||||
if !has_written_close {
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection_id.clone(),
|
||||
request_id: request_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
is_server: true,
|
||||
message_type: WebsocketEventType::Close,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_websocket_event(
|
||||
&WebsocketEvent {
|
||||
connection_id: connection_id.clone(),
|
||||
request_id: request_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
is_server: true,
|
||||
message_type: WebsocketEventType::Close,
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
app_handle
|
||||
.db()
|
||||
.upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
request_id: request_id.to_string(),
|
||||
state: WebsocketConnectionState::Closed,
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
.with_tx(|tx| {
|
||||
tx.upsert_websocket_connection(
|
||||
&WebsocketConnection {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
request_id: request_id.to_string(),
|
||||
state: WebsocketConnectionState::Closed,
|
||||
..connection
|
||||
},
|
||||
&UpdateSource::from_window_label(&window_label),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
@@ -461,7 +476,6 @@ pub async fn cmd_ws_connect<R: Runtime>(
|
||||
Ok(connection)
|
||||
}
|
||||
|
||||
|
||||
/// Convert WS URL to HTTP URL for cookie filtering
|
||||
/// WebSocket upgrade requests are HTTP requests initially, so HttpOnly cookies should apply
|
||||
fn convert_ws_url_to_http(ws_url: &Url) -> Url {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
# will have compiled files and executables
|
||||
target/
|
||||
|
||||
vendored/*
|
||||
|
||||
gen/*
|
||||
|
||||
**/permissions/autogenerated
|
||||
|
||||
@@ -14,12 +14,14 @@ tauri-build = { version = "2.6.1", features = [] }
|
||||
|
||||
[features]
|
||||
default = ["wry"]
|
||||
wry = ["tauri/wry", "tauri/x11", "tauri/dbus"]
|
||||
wry = ["tauri/wry", "tauri/x11", "tauri/dbus", "tauri-plugin-dialog/gtk3"]
|
||||
|
||||
[dependencies]
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true, features = ["devtools"] }
|
||||
tauri-plugin-dialog = { workspace = true }
|
||||
tauri-plugin-opener = "2.5.4"
|
||||
tauri-plugin-os = "2.3.2"
|
||||
yaak-mac-window = { workspace = true }
|
||||
yaak-proxy-lib = { workspace = true }
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
"windows": ["*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"dialog:allow-save",
|
||||
"opener:allow-default-urls",
|
||||
"opener:allow-open-url",
|
||||
"os:allow-os-type",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-is-fullscreen",
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Registered by the app with SMAppService.daemon(plistName:), approved once in
|
||||
System Settings > General > Login Items & Extensions. -->
|
||||
<key>Label</key>
|
||||
<string>app.yaak.proxy.helper</string>
|
||||
<key>BundleProgram</key>
|
||||
<string>Contents/MacOS/yaak-proxy-helper</string>
|
||||
<key>AssociatedBundleIdentifiers</key>
|
||||
<array>
|
||||
<string>app.yaak.proxy</string>
|
||||
<string>app.yaak.proxy.dev</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<!-- Restarted after a crash, not after a clean exit (unregistered, or stopped). -->
|
||||
<key>KeepAlive</key>
|
||||
<dict>
|
||||
<key>SuccessfulExit</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>/Library/Logs/app.yaak.proxy.helper.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- The hardened runtime with no exceptions. Not sandboxed: the app runs a local
|
||||
proxy server and changes the system proxy through its helper. -->
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -61,13 +61,30 @@ async fn rpc(
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_os::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(yaak_mac_window::init())
|
||||
.setup(|app| {
|
||||
let data_dir = app.path().app_data_dir().expect("no app data dir");
|
||||
std::fs::create_dir_all(&data_dir).expect("failed to create app data dir");
|
||||
|
||||
let (emitter, event_rx) = RpcEventEmitter::new();
|
||||
app.manage(ProxyCtx::new(&data_dir.join("proxy.db"), emitter));
|
||||
let ctx = ProxyCtx::new(&data_dir, emitter)?;
|
||||
// Not while the CLI daemon owns the engine: the window offers to take it over.
|
||||
match ctx.serve_control_api() {
|
||||
// The engine runs for as long as the app does. A failure, such as the port
|
||||
// being taken, is kept for the window to show.
|
||||
Ok(()) => {
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = ctx.start() {
|
||||
warn!("Failed to start the proxy: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => warn!("Not serving the proxy control API: {e}"),
|
||||
}
|
||||
app.manage(ctx);
|
||||
app.manage(yaak_proxy_lib::build_router());
|
||||
|
||||
// Drain RPC events and forward as Tauri events
|
||||
@@ -86,6 +103,13 @@ pub fn run() {
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building yaak proxy tauri application")
|
||||
.run(|app_handle, event| {
|
||||
if let RunEvent::Exit = event {
|
||||
// Never leave the Mac pointed at a proxy that is gone.
|
||||
let ctx = app_handle.state::<ProxyCtx>();
|
||||
ctx.shutdown();
|
||||
ctx.stop_control_api();
|
||||
return;
|
||||
}
|
||||
if let RunEvent::Ready = event {
|
||||
let config = CreateWindowConfig {
|
||||
url: "/",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
// Says what macOS reports about the privileged helper, without opening a window.
|
||||
if std::env::args().any(|a| a == "--helper-status") {
|
||||
println!("{}", yaak_proxy_lib::helper::diagnose());
|
||||
return;
|
||||
}
|
||||
tauri_app_proxy_lib::run();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"build": {
|
||||
"beforeBuildCommand": "npm --prefix ../.. run proxy:tauri-before-bundle"
|
||||
},
|
||||
"bundle": {
|
||||
"externalBin": ["vendored/helper/yaak-proxy-helper"],
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "13.0",
|
||||
"hardenedRuntime": true,
|
||||
"entitlements": "macos/entitlements.plist",
|
||||
"files": {
|
||||
"Library/LaunchDaemons/app.yaak.proxy.helper.plist": "macos/app.yaak.proxy.helper.plist"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow, is_dev};
|
||||
use ts_rs::TS;
|
||||
use yaak_api::{ApiClientKind, yaak_api_client};
|
||||
use yaak_common::platform::get_os_str;
|
||||
use yaak_models::client_db::ClientDb;
|
||||
use yaak_models::client_db::{ClientDb, WriteDb};
|
||||
use yaak_models::query_manager::QueryManager;
|
||||
use yaak_models::util::UpdateSource;
|
||||
|
||||
@@ -17,6 +17,10 @@ use yaak_models::util::UpdateSource;
|
||||
/// This is needed temporarily until all crates are refactored to not use Tauri.
|
||||
trait QueryManagerExt<'a, R> {
|
||||
fn db(&'a self) -> ClientDb<'a>;
|
||||
fn with_tx<T>(
|
||||
&'a self,
|
||||
func: impl FnOnce(&WriteDb) -> yaak_models::error::Result<T>,
|
||||
) -> yaak_models::error::Result<T>;
|
||||
}
|
||||
|
||||
impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
||||
@@ -24,6 +28,14 @@ impl<'a, R: Runtime, M: Manager<R>> QueryManagerExt<'a, R> for M {
|
||||
let qm = self.state::<QueryManager>();
|
||||
qm.inner().connect()
|
||||
}
|
||||
|
||||
fn with_tx<T>(
|
||||
&'a self,
|
||||
func: impl FnOnce(&WriteDb) -> yaak_models::error::Result<T>,
|
||||
) -> yaak_models::error::Result<T> {
|
||||
let qm = self.state::<QueryManager>();
|
||||
qm.inner().with_tx(func)
|
||||
}
|
||||
}
|
||||
|
||||
const KV_NAMESPACE: &str = "license";
|
||||
@@ -137,12 +149,17 @@ pub async fn activate_license<R: Runtime>(
|
||||
}
|
||||
|
||||
let body: ActivateLicenseResponsePayload = response.json().await?;
|
||||
window.app_handle().db().set_key_value_str(
|
||||
KV_ACTIVATION_ID_KEY,
|
||||
KV_NAMESPACE,
|
||||
body.activation_id.as_str(),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
);
|
||||
if let Err(e) = window.app_handle().with_tx(|tx| {
|
||||
tx.set_key_value_str(
|
||||
KV_ACTIVATION_ID_KEY,
|
||||
KV_NAMESPACE,
|
||||
body.activation_id.as_str(),
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
);
|
||||
Ok(())
|
||||
}) {
|
||||
warn!("Failed to store license activation: {e}");
|
||||
}
|
||||
|
||||
if let Err(e) = window.emit("license-activated", true) {
|
||||
warn!("Failed to emit check-license event: {}", e);
|
||||
@@ -172,11 +189,13 @@ pub async fn deactivate_license<R: Runtime>(window: &WebviewWindow<R>) -> Result
|
||||
return Err(ServerError);
|
||||
}
|
||||
|
||||
app_handle.db().delete_key_value(
|
||||
KV_ACTIVATION_ID_KEY,
|
||||
KV_NAMESPACE,
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)?;
|
||||
app_handle.with_tx(|tx| {
|
||||
tx.delete_key_value(
|
||||
KV_ACTIVATION_ID_KEY,
|
||||
KV_NAMESPACE,
|
||||
&UpdateSource::from_window_label(window.label()),
|
||||
)
|
||||
})?;
|
||||
|
||||
if let Err(e) = app_handle.emit("license-deactivated", true) {
|
||||
warn!("Failed to emit deactivate-license event: {}", e);
|
||||
|
||||
@@ -12,11 +12,11 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("cargo-cli
|
||||
tauri-plugin = { workspace = true, features = ["build"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
cocoa = "0.26.0"
|
||||
cocoa = "0.27.0"
|
||||
log = { workspace = true }
|
||||
objc = "0.2.7"
|
||||
rand = "0.9.0"
|
||||
csscolorparser = "0.7.2"
|
||||
rand = "0.10.2"
|
||||
csscolorparser = "0.9.0"
|
||||
|
||||
[dependencies]
|
||||
tauri = { workspace = true }
|
||||
@@ -147,7 +147,7 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
|
||||
use cocoa::delegate;
|
||||
use cocoa::foundation::NSUInteger;
|
||||
use objc::runtime::{Object, Sel};
|
||||
use rand::Rng;
|
||||
use rand::RngExt;
|
||||
use rand::distr::Alphanumeric;
|
||||
use std::ffi::c_void;
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "yaak-proxy-helper"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
authors = ["Gregory Schier"]
|
||||
publish = false
|
||||
|
||||
# The library is the protocol and the `networksetup` logic, shared with `yaak-proxy-lib`, and
|
||||
# builds everywhere. The daemon itself is macOS only.
|
||||
[lib]
|
||||
name = "yaak_proxy_helper"
|
||||
|
||||
[[bin]]
|
||||
name = "yaak-proxy-helper"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
# TypeScript bindings for the types the proxy app shows.
|
||||
ts = ["dep:ts-rs"]
|
||||
# An in-memory `networksetup`, for tests that change the system proxy.
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
ts-rs = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-foundation = "0.10"
|
||||
libc = "0.2"
|
||||
security-framework = "3"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Who is on the other end of the socket. The kernel says which process connected, by its
|
||||
//! audit token, and Security.framework says whether that process is the proxy app signed by
|
||||
//! [`crate::TEAM_ID`]. The token, unlike a pid, cannot be recycled for another process
|
||||
//! between the two.
|
||||
|
||||
use core_foundation::base::TCFType;
|
||||
use core_foundation::data::CFData;
|
||||
use security_framework::os::macos::code_signing::{
|
||||
Flags, GuestAttributes, SecCode, SecRequirement,
|
||||
};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// The process that connected.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Peer {
|
||||
pub pid: i32,
|
||||
/// Its `audit_token_t`.
|
||||
pub audit_token: [u8; 32],
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
pub fn of(stream: &UnixStream) -> Result<Self, String> {
|
||||
let fd = stream.as_raw_fd();
|
||||
let mut pid: libc::pid_t = 0;
|
||||
let mut len = std::mem::size_of::<libc::pid_t>() as libc::socklen_t;
|
||||
// SAFETY: `pid` and `len` describe a buffer the size LOCAL_PEERPID writes.
|
||||
let rc = unsafe {
|
||||
libc::getsockopt(
|
||||
fd,
|
||||
libc::SOL_LOCAL,
|
||||
libc::LOCAL_PEERPID,
|
||||
(&mut pid as *mut libc::pid_t).cast(),
|
||||
&mut len,
|
||||
)
|
||||
};
|
||||
if rc != 0 {
|
||||
return Err(format!(
|
||||
"Failed to read the peer pid: {}",
|
||||
std::io::Error::last_os_error()
|
||||
));
|
||||
}
|
||||
let mut audit_token = [0u8; 32];
|
||||
let mut len = audit_token.len() as libc::socklen_t;
|
||||
// SAFETY: as above, for the 32-byte audit_token_t LOCAL_PEERTOKEN writes.
|
||||
let rc = unsafe {
|
||||
libc::getsockopt(
|
||||
fd,
|
||||
libc::SOL_LOCAL,
|
||||
libc::LOCAL_PEERTOKEN,
|
||||
audit_token.as_mut_ptr().cast(),
|
||||
&mut len,
|
||||
)
|
||||
};
|
||||
if rc != 0 || len as usize != audit_token.len() {
|
||||
return Err(format!(
|
||||
"Failed to read the peer's audit token: {}",
|
||||
std::io::Error::last_os_error()
|
||||
));
|
||||
}
|
||||
Ok(Self { pid, audit_token })
|
||||
}
|
||||
}
|
||||
|
||||
/// Decides whether a peer may use the daemon.
|
||||
pub trait Verifier: Send + Sync {
|
||||
fn verify(&self, peer: &Peer) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// The real check: the peer's code signature against [`crate::code_requirement`].
|
||||
pub struct CodeSignature {
|
||||
requirement: String,
|
||||
}
|
||||
|
||||
impl Default for CodeSignature {
|
||||
fn default() -> Self {
|
||||
Self { requirement: crate::code_requirement() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Verifier for CodeSignature {
|
||||
fn verify(&self, peer: &Peer) -> Result<(), String> {
|
||||
let refused = |why: String| format!("Refused pid {}: {why}", peer.pid);
|
||||
let token = CFData::from_buffer(&peer.audit_token);
|
||||
let mut attributes = GuestAttributes::new();
|
||||
attributes.set_audit_token(token.as_concrete_TypeRef());
|
||||
let code = SecCode::copy_guest_with_attribues(None, &attributes, Flags::NONE)
|
||||
.map_err(|e| refused(format!("no code object ({e})")))?;
|
||||
let requirement = SecRequirement::from_str(&self.requirement)
|
||||
.map_err(|e| format!("Invalid code requirement: {e}"))?;
|
||||
code.check_validity(Flags::NONE, &requirement)
|
||||
.map_err(|e| refused(format!("not Yaak Proxy signed by {} ({e})", crate::TEAM_ID)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_the_peer_and_refuses_code_not_signed_as_the_app() {
|
||||
// This test binary is the peer: at most ad-hoc signed, never the proxy app.
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
let peer = Peer::of(&a).unwrap();
|
||||
assert_eq!(peer.pid, std::process::id() as i32);
|
||||
assert_ne!(peer.audit_token, [0; 32]);
|
||||
let err = CodeSignature::default().verify(&peer).unwrap_err();
|
||||
assert!(err.starts_with(&format!("Refused pid {}", peer.pid)), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_requirement_naming_another_team_refuses_too() {
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
let peer = Peer::of(&a).unwrap();
|
||||
let verifier = CodeSignature {
|
||||
requirement: "anchor apple generic and identifier \"app.yaak.proxy\" and certificate leaf[subject.OU] = \"AAAAAAAAAA\"".into(),
|
||||
};
|
||||
assert!(verifier.verify(&peer).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
//! The daemon: serves the socket, keeps the saved settings in its state file, and restores
|
||||
//! them when the process that turned the system proxy on exits, crashes included.
|
||||
|
||||
use crate::auth::{CodeSignature, Peer, Verifier};
|
||||
use crate::networksetup::{
|
||||
Networksetup, Snapshot, SystemNetworksetup, apply, disable_commands, enable_commands,
|
||||
read_services,
|
||||
};
|
||||
use crate::process::{Owner, Processes, SystemProcesses};
|
||||
use crate::protocol::{MAX_LINE, Request, Response, Status, parse_request};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How often the owner is checked on.
|
||||
const WATCH_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Long enough for `networksetup` on every service, short enough that a silent caller lets go.
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// What the daemon has done, saved to its state file before each change, so a daemon that
|
||||
/// crashes or restarts still knows what to put back.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct State {
|
||||
pub active: Option<Active>,
|
||||
/// Saved settings a restore found no service for, a service removed or unplugged, kept
|
||||
/// for when it is back and merged into the next capture.
|
||||
#[serde(default)]
|
||||
pub parked: Option<Snapshot>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Active {
|
||||
pub owner: Owner,
|
||||
pub snapshot: Snapshot,
|
||||
}
|
||||
|
||||
pub struct Daemon<N, P> {
|
||||
ns: N,
|
||||
processes: P,
|
||||
state_path: PathBuf,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
impl<N: Networksetup, P: Processes> Daemon<N, P> {
|
||||
/// Starts from the state file at `state_path`, or from nothing.
|
||||
pub fn open(ns: N, processes: P, state_path: PathBuf) -> Self {
|
||||
let state = match std::fs::read(&state_path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||
log(&format!("Ignoring an unreadable state file: {e}"));
|
||||
State::default()
|
||||
}),
|
||||
Err(_) => State::default(),
|
||||
};
|
||||
Self { ns, processes, state_path, state: Mutex::new(state) }
|
||||
}
|
||||
|
||||
pub fn state(&self) -> State {
|
||||
self.lock().clone()
|
||||
}
|
||||
|
||||
pub fn handle(&self, request: &Request) -> Response {
|
||||
let result = match *request {
|
||||
Request::Get => Ok(status(&self.lock())),
|
||||
Request::Set { enabled: true, port, owner_pid } => self.enable(port, owner_pid),
|
||||
Request::Set { enabled: false, port, .. } => self.restore(Some(port)),
|
||||
Request::Restore => self.restore(None),
|
||||
Request::Unregister => self.unregister(),
|
||||
};
|
||||
match result {
|
||||
Ok(status) => Response::ok(status),
|
||||
Err(e) => Response::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Points every enabled service at `port`, saving what it replaces first, unless an
|
||||
/// earlier enable already did and nothing was restored since.
|
||||
fn enable(&self, port: u16, owner_pid: i32) -> Result<Status, String> {
|
||||
let owner = self
|
||||
.processes
|
||||
.owner(owner_pid)
|
||||
.ok_or_else(|| format!("The owner, pid {owner_pid}, is not running"))?;
|
||||
let mut state = self.lock();
|
||||
let services = read_services(&self.ns, false)?;
|
||||
let mut snapshot = match state.active.take() {
|
||||
Some(active) => active.snapshot,
|
||||
None => state.parked.take().unwrap_or_default(),
|
||||
};
|
||||
snapshot.extend(&services, port);
|
||||
state.active = Some(Active { owner, snapshot });
|
||||
// Saved before anything changes, so whatever happens next can be undone.
|
||||
self.save(&state)?;
|
||||
if let Err(e) = apply(&self.ns, &enable_commands(&services, port)) {
|
||||
// Half applied is worse than not at all.
|
||||
if let Err(undo) = self.restore_locked(&mut state, None) {
|
||||
log(&format!("Failed to undo a partial change: {undo}"));
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(status(&state))
|
||||
}
|
||||
|
||||
/// Turns the system proxy off at `port`, or wherever it points without one: at the saved
|
||||
/// port this puts back everything saved; at another, a stale one, it only turns off what
|
||||
/// points there, and the saved settings stay with the routing still live.
|
||||
fn restore(&self, port: Option<u16>) -> Result<Status, String> {
|
||||
let mut state = self.lock();
|
||||
self.restore_locked(&mut state, port)?;
|
||||
Ok(status(&state))
|
||||
}
|
||||
|
||||
fn restore_locked(&self, state: &mut State, port: Option<u16>) -> Result<(), String> {
|
||||
let port = port.unwrap_or(0);
|
||||
let snapshot = state.active.as_ref().map(|a| &a.snapshot);
|
||||
if snapshot.is_none() && port == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let services = read_services(&self.ns, true)?;
|
||||
let (commands, used_up) = disable_commands(&services, snapshot, port);
|
||||
// Saved first, so a restore cut short is finished by the next one.
|
||||
if let Some(active) = state.active.as_mut() {
|
||||
active.snapshot.mark_restoring(&commands, &services);
|
||||
self.save(state)?;
|
||||
}
|
||||
// Kept on failure, so the next try still knows what to put back.
|
||||
apply(&self.ns, &commands)?;
|
||||
if used_up {
|
||||
if let Some(active) = state.active.take()
|
||||
&& let Some(leftover) = active.snapshot.leftover(&services)
|
||||
{
|
||||
let names: Vec<&str> = leftover.services.iter().map(|s| s.name.as_str()).collect();
|
||||
log(&format!("Keeping saved settings no service matched: {}", names.join(", ")));
|
||||
state.parked = Some(leftover);
|
||||
}
|
||||
} else if let Some(active) = state.active.as_mut() {
|
||||
active.snapshot.restoring.clear();
|
||||
}
|
||||
self.save(state)
|
||||
}
|
||||
|
||||
/// Restores, then deletes the state file, as the app is about to remove the daemon. Saved
|
||||
/// settings no service matched stay in it, for a daemon registered again.
|
||||
fn unregister(&self) -> Result<Status, String> {
|
||||
let mut state = self.lock();
|
||||
self.restore_locked(&mut state, None)?;
|
||||
if state.parked.is_some() {
|
||||
return Ok(status(&state));
|
||||
}
|
||||
match std::fs::remove_file(&self.state_path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("Failed to delete the state file: {e}")),
|
||||
}
|
||||
Ok(status(&state))
|
||||
}
|
||||
|
||||
/// One look at the owner: restores once it has exited. True when it restored.
|
||||
pub fn watch(&self) -> bool {
|
||||
let mut state = self.lock();
|
||||
let Some(active) = &state.active else {
|
||||
return false;
|
||||
};
|
||||
if self.processes.is_alive(&active.owner) {
|
||||
return false;
|
||||
}
|
||||
log(&format!("The owner, pid {}, exited; restoring the system proxy", active.owner.pid));
|
||||
match self.restore_locked(&mut state, None) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log(&format!("Failed to restore the system proxy: {e}"));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, state: &State) -> Result<(), String> {
|
||||
let json = serde_json::to_vec_pretty(state).map_err(|e| e.to_string())?;
|
||||
let tmp = self.state_path.with_extension("tmp");
|
||||
std::fs::write(&tmp, json)
|
||||
.and_then(|()| std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)))
|
||||
.and_then(|()| std::fs::rename(&tmp, &self.state_path))
|
||||
.map_err(|e| format!("Failed to save the helper's state: {e}"))
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
// A panic mid-change leaves the state as saved, which is still the truth to restore.
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
fn status(state: &State) -> Status {
|
||||
Status {
|
||||
active: state.active.is_some(),
|
||||
port: state.active.as_ref().map(|a| a.snapshot.port),
|
||||
owner_pid: state.active.as_ref().map(|a| a.owner.pid),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many connections are served at once. The app needs one; more are refused.
|
||||
pub const MAX_CONNECTIONS: usize = 4;
|
||||
|
||||
/// A counting semaphore for connections being served.
|
||||
pub struct Slots {
|
||||
taken: Arc<AtomicUsize>,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
/// A connection's place among [`Slots`], given back when dropped.
|
||||
pub struct Slot(Arc<AtomicUsize>);
|
||||
|
||||
impl Drop for Slot {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Slots {
|
||||
pub fn new(max: usize) -> Self {
|
||||
Self { taken: Arc::new(AtomicUsize::new(0)), max }
|
||||
}
|
||||
|
||||
/// A slot, unless all are taken.
|
||||
pub fn try_take(&self) -> Option<Slot> {
|
||||
let max = self.max;
|
||||
self.taken
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| (n < max).then_some(n + 1))
|
||||
.ok()
|
||||
.map(|_| Slot(self.taken.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes a connection on, before any thread is spawned for it: a free slot, and the kernel's
|
||||
/// word on who is calling. Both are cheap; the signature check is not, so it runs in the
|
||||
/// connection's own thread.
|
||||
pub fn admit(stream: &UnixStream, slots: &Slots) -> Result<(Peer, Slot), String> {
|
||||
let slot = slots.try_take().ok_or("The helper is busy; try again")?;
|
||||
let peer = Peer::of(stream)?;
|
||||
Ok((peer, slot))
|
||||
}
|
||||
|
||||
/// Answers a connection that was not admitted with why, briefly, before it is closed.
|
||||
fn refuse(stream: &UnixStream, why: &str) {
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(1)));
|
||||
let mut line = serde_json::to_string(&Response::error(why)).unwrap_or_default();
|
||||
line.push('\n');
|
||||
let mut writer = stream;
|
||||
let _ = writer.write_all(line.as_bytes());
|
||||
}
|
||||
|
||||
/// Answers one connection's requests, one line each, once the peer passes `verifier`. An
|
||||
/// unregister leaves the daemon running: it stops when macOS confirms the unregistration, and
|
||||
/// if that never comes, it is still there to answer.
|
||||
pub fn serve_connection<N: Networksetup, P: Processes>(
|
||||
stream: UnixStream,
|
||||
peer: Peer,
|
||||
daemon: &Daemon<N, P>,
|
||||
verifier: &dyn Verifier,
|
||||
) {
|
||||
let _ = stream.set_read_timeout(Some(IO_TIMEOUT));
|
||||
let _ = stream.set_write_timeout(Some(IO_TIMEOUT));
|
||||
let mut writer = &stream;
|
||||
let mut reply = |response: &Response| {
|
||||
let mut line = serde_json::to_string(response).unwrap_or_default();
|
||||
line.push('\n');
|
||||
writer.write_all(line.as_bytes()).is_ok()
|
||||
};
|
||||
|
||||
if let Err(e) = verifier.verify(&peer) {
|
||||
log(&e);
|
||||
reply(&Response::error(e));
|
||||
return;
|
||||
}
|
||||
|
||||
let mut reader = BufReader::new(&stream);
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
match (&mut reader).take(MAX_LINE as u64).read_line(&mut line) {
|
||||
Ok(0) => return,
|
||||
Ok(_) if !line.ends_with('\n') => {
|
||||
reply(&Response::error("Request too long or unterminated"));
|
||||
return;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => return,
|
||||
}
|
||||
let response = match parse_request(&line) {
|
||||
Ok(request) => {
|
||||
log(&format!("pid {}: {request:?}", peer.pid));
|
||||
daemon.handle(&request)
|
||||
}
|
||||
Err(e) => Response::error(e),
|
||||
};
|
||||
if !reply(&response) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The daemon's entry point, run by launchd as root. Returns the exit code.
|
||||
pub fn run() -> i32 {
|
||||
// SAFETY: geteuid has no preconditions.
|
||||
if unsafe { libc::geteuid() } != 0 {
|
||||
eprintln!("yaak-proxy-helper is started by launchd, as root");
|
||||
return 1;
|
||||
}
|
||||
// Blocked before any thread starts, so every thread inherits it and only `sigwait` sees
|
||||
// them.
|
||||
let signals = blocked_signals();
|
||||
|
||||
let state_dir = Path::new(crate::STATE_DIR);
|
||||
if let Err(e) = std::fs::create_dir_all(state_dir)
|
||||
.and_then(|()| std::fs::set_permissions(state_dir, std::fs::Permissions::from_mode(0o700)))
|
||||
{
|
||||
log(&format!("Failed to create {}: {e}", state_dir.display()));
|
||||
return 1;
|
||||
}
|
||||
let daemon =
|
||||
Arc::new(Daemon::open(SystemNetworksetup, SystemProcesses, state_dir.join("state.json")));
|
||||
// The owner may have exited while the daemon was down.
|
||||
daemon.watch();
|
||||
|
||||
let _ = std::fs::remove_file(crate::SOCKET_PATH);
|
||||
let listener = match UnixListener::bind(crate::SOCKET_PATH) {
|
||||
Ok(listener) => listener,
|
||||
Err(e) => {
|
||||
log(&format!("Failed to listen on {}: {e}", crate::SOCKET_PATH));
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
// Anyone may connect; only the signed app is answered.
|
||||
let _ = std::fs::set_permissions(crate::SOCKET_PATH, std::fs::Permissions::from_mode(0o666));
|
||||
log(&format!("Listening on {}", crate::SOCKET_PATH));
|
||||
|
||||
let watched = daemon.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(WATCH_INTERVAL);
|
||||
watched.watch();
|
||||
}
|
||||
});
|
||||
|
||||
let stopping = daemon.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut signal = 0;
|
||||
// SAFETY: `signals` is an initialised set, and `signal` a valid out pointer.
|
||||
unsafe { libc::sigwait(&signals, &mut signal) };
|
||||
// Stopped by launchd: unregistered in System Settings, or the Mac shutting down.
|
||||
log(&format!("Signal {signal}; restoring the system proxy and exiting"));
|
||||
if let Response { ok: false, error: Some(e), .. } = stopping.handle(&Request::Restore) {
|
||||
log(&format!("Failed to restore the system proxy: {e}"));
|
||||
}
|
||||
exit();
|
||||
});
|
||||
|
||||
let verifier: Arc<dyn Verifier> = Arc::new(CodeSignature::default());
|
||||
let slots = Slots::new(MAX_CONNECTIONS);
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else {
|
||||
continue;
|
||||
};
|
||||
let (peer, slot) = match admit(&stream, &slots) {
|
||||
Ok(admitted) => admitted,
|
||||
Err(why) => {
|
||||
log(&why);
|
||||
refuse(&stream, &why);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let daemon = daemon.clone();
|
||||
let verifier = verifier.clone();
|
||||
let spawned = std::thread::Builder::new().spawn(move || {
|
||||
let _slot = slot;
|
||||
serve_connection(stream, peer, &daemon, verifier.as_ref());
|
||||
});
|
||||
// The closure, and with it the connection and its slot, is dropped: closed and freed.
|
||||
if let Err(e) = spawned {
|
||||
log(&format!("Failed to start a thread for pid {}: {e}", peer.pid));
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// Exits cleanly, which launchd does not restart.
|
||||
fn exit() -> ! {
|
||||
let _ = std::fs::remove_file(crate::SOCKET_PATH);
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
fn blocked_signals() -> libc::sigset_t {
|
||||
// SAFETY: the set is initialised by sigemptyset before use, and only signal numbers are
|
||||
// added to it.
|
||||
unsafe {
|
||||
let mut set = std::mem::zeroed::<libc::sigset_t>();
|
||||
libc::sigemptyset(&mut set);
|
||||
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
|
||||
libc::sigaddset(&mut set, signal);
|
||||
}
|
||||
libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
fn log(message: &str) {
|
||||
eprintln!(
|
||||
"{} {message}",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or_default()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::networksetup::fake::FakeNetworksetup;
|
||||
use crate::networksetup::{HOST, ProxySetting};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Processes that are alive while listed.
|
||||
#[derive(Default)]
|
||||
struct FakeProcesses(Mutex<HashMap<i32, u64>>);
|
||||
|
||||
impl FakeProcesses {
|
||||
fn start(&self, pid: i32, started: u64) {
|
||||
self.0.lock().unwrap().insert(pid, started);
|
||||
}
|
||||
fn kill(&self, pid: i32) {
|
||||
self.0.lock().unwrap().remove(&pid);
|
||||
}
|
||||
}
|
||||
|
||||
impl Processes for FakeProcesses {
|
||||
fn start_time(&self, pid: i32) -> Option<u64> {
|
||||
self.0.lock().unwrap().get(&pid).copied()
|
||||
}
|
||||
}
|
||||
|
||||
struct Allow;
|
||||
impl Verifier for Allow {
|
||||
fn verify(&self, _peer: &Peer) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Refuse;
|
||||
impl Verifier for Refuse {
|
||||
fn verify(&self, peer: &Peer) -> Result<(), String> {
|
||||
Err(format!("Refused pid {}: not Yaak Proxy", peer.pid))
|
||||
}
|
||||
}
|
||||
|
||||
fn setting(enabled: bool, server: &str, port: u16) -> ProxySetting {
|
||||
ProxySetting { enabled, server: server.into(), port }
|
||||
}
|
||||
|
||||
fn daemon(dir: &Path) -> Daemon<FakeNetworksetup, FakeProcesses> {
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", setting(true, "corp-proxy", 3128), setting(false, "corp-proxy", 3129)),
|
||||
("Ethernet", ProxySetting::default(), ProxySetting::default()),
|
||||
]);
|
||||
let processes = FakeProcesses::default();
|
||||
processes.start(42, 1000);
|
||||
Daemon::open(ns, processes, dir.join("state.json"))
|
||||
}
|
||||
|
||||
fn set(enabled: bool, port: u16) -> Request {
|
||||
Request::Set { enabled, port, owner_pid: 42 }
|
||||
}
|
||||
|
||||
fn all_point_at(daemon: &Daemon<FakeNetworksetup, FakeProcesses>, port: u16) -> bool {
|
||||
daemon.ns.proxies().iter().all(|s| s.http.points_at(port) && s.https.points_at(port))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_then_off_restores_exactly() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
|
||||
let status = daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
assert!(status.active && status.port == Some(9090) && status.owner_pid == Some(42));
|
||||
assert!(all_point_at(&daemon, 9090));
|
||||
|
||||
let status = daemon.handle(&set(false, 9090)).into_result().unwrap();
|
||||
assert!(!status.active);
|
||||
assert_eq!(daemon.ns.proxies()[0], before[0]);
|
||||
assert!(!daemon.ns.proxies()[1].points_at(9090));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snapshot_survives_a_daemon_restart() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let first = daemon(dir.path());
|
||||
let before = first.ns.proxies();
|
||||
first.handle(&set(true, 9090)).into_result().unwrap();
|
||||
let saved = first.state();
|
||||
assert!(saved.active.is_some());
|
||||
|
||||
// A new daemon over the same machine reads what the first saved.
|
||||
let second = Daemon::open(
|
||||
FakeNetworksetup::default(),
|
||||
FakeProcesses::default(),
|
||||
dir.path().join("state.json"),
|
||||
);
|
||||
assert_eq!(second.state(), saved);
|
||||
*second.ns.services.lock().unwrap() = first.ns.services.lock().unwrap().clone();
|
||||
second.handle(&Request::Restore).into_result().unwrap();
|
||||
assert_eq!(second.ns.proxies()[0], before[0]);
|
||||
assert_eq!(second.state(), State::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_twice_keeps_the_first_snapshot() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
// The engine moved ports; what was saved is still the user's.
|
||||
daemon.handle(&set(true, 9191)).into_result().unwrap();
|
||||
assert!(all_point_at(&daemon, 9191));
|
||||
daemon.handle(&Request::Restore).into_result().unwrap();
|
||||
assert_eq!(daemon.ns.proxies()[0], before[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_port_move_still_restores_the_old_port() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
// Moving to 9191 fails on Ethernet, after Wi-Fi moved.
|
||||
*daemon.ns.failing.lock().unwrap() = Some("Ethernet".into());
|
||||
assert!(!daemon.handle(&set(true, 9191)).ok);
|
||||
// The undo failed on Ethernet too, so what to put back is kept for the next try.
|
||||
assert!(daemon.state().active.is_some());
|
||||
*daemon.ns.failing.lock().unwrap() = None;
|
||||
daemon.handle(&Request::Restore).into_result().unwrap();
|
||||
// Restored everywhere, the old port included.
|
||||
assert_eq!(daemon.ns.proxies()[0], before[0]);
|
||||
assert!(!daemon.ns.proxies()[1].points_at(9090));
|
||||
assert_eq!(daemon.state(), State::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_off_a_stale_port_keeps_the_live_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
daemon.ns.set_enabled("Ethernet", false);
|
||||
daemon.handle(&set(true, 9191)).into_result().unwrap();
|
||||
|
||||
// The app's launch cleanup of its old port.
|
||||
let status = daemon.handle(&set(false, 9090)).into_result().unwrap();
|
||||
assert!(status.active && status.port == Some(9191));
|
||||
assert!(daemon.ns.proxies()[0].http.points_at(9191));
|
||||
assert!(!daemon.ns.proxies()[1].points_at(9090));
|
||||
|
||||
daemon.handle(&set(false, 9191)).into_result().unwrap();
|
||||
assert_eq!(daemon.ns.proxies()[0], before[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_service_renamed_while_routing_is_restored() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
daemon.ns.rename("Wi-Fi", "Office Wi-Fi");
|
||||
daemon.handle(&set(false, 9090)).into_result().unwrap();
|
||||
let after = &daemon.ns.proxies()[0];
|
||||
assert_eq!((&after.http, &after.https), (&before[0].http, &before[0].https));
|
||||
assert_eq!(daemon.state(), State::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_no_service_matched_are_parked_and_merged_back() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let wifi = daemon.ns.proxies()[0].clone();
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
// Wi-Fi is unplugged while ours is on.
|
||||
daemon.ns.remove("Wi-Fi");
|
||||
daemon.handle(&set(false, 9090)).into_result().unwrap();
|
||||
let parked = daemon.state().parked.unwrap();
|
||||
assert_eq!(parked.services.len(), 1);
|
||||
assert_eq!(parked.services[0].http, wifi.http);
|
||||
|
||||
// Kept through unregister, and back in the next capture.
|
||||
daemon.handle(&Request::Unregister).into_result().unwrap();
|
||||
assert!(dir.path().join("state.json").exists());
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
let state = daemon.state();
|
||||
assert!(state.parked.is_none());
|
||||
assert!(state.active.unwrap().snapshot.services.iter().any(|s| s.http == wifi.http));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_watchdog_restores_once_the_owner_exits() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
|
||||
assert!(!daemon.watch(), "the owner is alive");
|
||||
assert!(all_point_at(&daemon, 9090));
|
||||
|
||||
daemon.processes.kill(42);
|
||||
assert!(daemon.watch());
|
||||
assert_eq!(daemon.ns.proxies()[0], before[0]);
|
||||
assert!(!daemon.watch(), "nothing left to restore");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_watchdog_treats_a_reused_pid_as_gone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
// The owner exited and another process got its pid.
|
||||
daemon.processes.start(42, 2000);
|
||||
assert!(daemon.watch());
|
||||
assert!(!daemon.ns.proxies()[1].points_at(9090));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_an_owner_that_is_not_running() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let err = daemon.handle(&Request::Set { enabled: true, port: 9090, owner_pid: 7 });
|
||||
assert!(!err.ok);
|
||||
assert!(daemon.ns.changes.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_enable_undoes_what_it_did() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let before = daemon.ns.proxies();
|
||||
// Ethernet goes away mid-change, after Wi-Fi was pointed at us.
|
||||
*daemon.ns.failing.lock().unwrap() = Some("Ethernet".into());
|
||||
assert!(!daemon.handle(&set(true, 9090)).ok);
|
||||
assert_eq!(daemon.ns.proxies(), before);
|
||||
assert_eq!(daemon.state(), State::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregister_restores_and_deletes_the_state_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
daemon.handle(&set(true, 9090)).into_result().unwrap();
|
||||
assert!(dir.path().join("state.json").exists());
|
||||
daemon.handle(&Request::Unregister).into_result().unwrap();
|
||||
assert!(!dir.path().join("state.json").exists());
|
||||
assert!(!daemon.ns.proxies()[0].points_at(9090));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_reports_without_changing_anything() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let status = daemon.handle(&Request::Get).into_result().unwrap();
|
||||
assert!(!status.active);
|
||||
assert!(daemon.ns.changes.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
fn exchange(verifier: &dyn Verifier, lines: &[&str]) -> (Vec<Response>, Vec<ProxySetting>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let daemon = daemon(dir.path());
|
||||
let (server, mut client) = UnixStream::pair().unwrap();
|
||||
for line in lines {
|
||||
client.write_all(format!("{line}\n").as_bytes()).unwrap();
|
||||
}
|
||||
client.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
let peer = Peer::of(&server).unwrap();
|
||||
serve_connection(server, peer, &daemon, verifier);
|
||||
let mut out = String::new();
|
||||
client.read_to_string(&mut out).unwrap();
|
||||
let responses = out.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
let http = daemon.ns.proxies().into_iter().map(|s| s.http).collect();
|
||||
(responses, http)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serves_a_verified_peer_line_by_line() {
|
||||
let pid = std::process::id() as i32;
|
||||
let (responses, http) = exchange(
|
||||
&AllowWithOwner(pid),
|
||||
&[
|
||||
r#"{"cmd":"get"}"#,
|
||||
r#"{"cmd":"set","enabled":true,"port":80,"owner_pid":42}"#,
|
||||
r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":42}"#,
|
||||
],
|
||||
);
|
||||
assert_eq!(responses.len(), 3);
|
||||
assert!(responses[0].ok && !responses[1].ok && responses[2].ok);
|
||||
assert!(http.iter().all(|s| s.server == HOST && s.port == 9090));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_an_unverified_peer_before_reading_anything() {
|
||||
let (responses, http) =
|
||||
exchange(&Refuse, &[r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":42}"#]);
|
||||
assert_eq!(responses.len(), 1);
|
||||
assert!(responses[0].error.as_deref().unwrap().starts_with("Refused pid"));
|
||||
assert!(http.iter().all(|s| s.server != HOST));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_peer_with_the_real_check() {
|
||||
// The test binary is not the signed app.
|
||||
let (responses, http) = exchange(&CodeSignature::default(), &[r#"{"cmd":"restore"}"#]);
|
||||
assert!(!responses[0].ok);
|
||||
assert!(http.iter().all(|s| s.server != HOST));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_answering_after_unregister() {
|
||||
// Should macOS fail to unregister it, the app can still reach it.
|
||||
let (responses, _) = exchange(
|
||||
&Allow,
|
||||
&[
|
||||
r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":42}"#,
|
||||
r#"{"cmd":"unregister"}"#,
|
||||
r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":42}"#,
|
||||
],
|
||||
);
|
||||
assert_eq!(responses.len(), 3);
|
||||
assert!(responses.iter().all(|r| r.ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slots_cap_connections_and_free_on_drop() {
|
||||
let slots = Slots::new(2);
|
||||
let a = slots.try_take().unwrap();
|
||||
let _b = slots.try_take().unwrap();
|
||||
assert!(slots.try_take().is_none());
|
||||
drop(a);
|
||||
assert!(slots.try_take().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_connection_over_the_cap_with_a_short_reply() {
|
||||
let slots = Slots::new(MAX_CONNECTIONS);
|
||||
let held: Vec<_> = (0..MAX_CONNECTIONS).map(|_| slots.try_take().unwrap()).collect();
|
||||
let (server, mut client) = UnixStream::pair().unwrap();
|
||||
let why = admit(&server, &slots).err().unwrap();
|
||||
refuse(&server, &why);
|
||||
drop(server);
|
||||
let mut out = String::new();
|
||||
client.read_to_string(&mut out).unwrap();
|
||||
let response: Response = serde_json::from_str(out.trim()).unwrap();
|
||||
assert_eq!(response.error.as_deref(), Some("The helper is busy; try again"));
|
||||
|
||||
// Admitted again once one is free, with the peer read before any thread runs.
|
||||
drop(held);
|
||||
let (server, _client) = UnixStream::pair().unwrap();
|
||||
let (peer, _slot) = admit(&server, &slots).unwrap();
|
||||
assert_eq!(peer.pid, std::process::id() as i32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_reading_an_overlong_line() {
|
||||
let long = format!(r#"{{"cmd":"get","x":"{}"}}"#, "a".repeat(MAX_LINE));
|
||||
let (responses, _) = exchange(&Allow, &[&long, r#"{"cmd":"get"}"#]);
|
||||
assert_eq!(responses.len(), 1);
|
||||
assert!(!responses[0].ok);
|
||||
}
|
||||
|
||||
/// Allows only the expected peer, this test process.
|
||||
struct AllowWithOwner(i32);
|
||||
impl Verifier for AllowWithOwner {
|
||||
fn verify(&self, peer: &Peer) -> Result<(), String> {
|
||||
if peer.pid == self.0 { Ok(()) } else { Err("wrong peer".into()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! Yaak Proxy's privileged helper: a root launchd daemon, registered by the app through
|
||||
//! `SMAppService`, that points this Mac's web proxies at the engine and puts the user's own
|
||||
//! settings back afterwards, so toggling the system proxy never asks for a password.
|
||||
//!
|
||||
//! The app talks to it over a Unix socket, one JSON line per request ([`protocol`]). Only a
|
||||
//! caller signed as the proxy app by [`TEAM_ID`] is served.
|
||||
|
||||
pub mod networksetup;
|
||||
pub mod protocol;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod auth;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod daemon;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod process;
|
||||
|
||||
/// The launchd label, which is also the plist's name without `.plist`.
|
||||
pub const LABEL: &str = "app.yaak.proxy.helper";
|
||||
|
||||
/// The plist inside the app, at `Contents/Library/LaunchDaemons/`.
|
||||
pub const PLIST_NAME: &str = "app.yaak.proxy.helper.plist";
|
||||
|
||||
/// Created by the daemon, root-owned and world-writable: who may talk is decided per caller.
|
||||
pub const SOCKET_PATH: &str = "/var/run/app.yaak.proxy.helper.sock";
|
||||
|
||||
/// The daemon's own state, root only: the settings to restore, and whose they are.
|
||||
pub const STATE_DIR: &str = "/var/db/app.yaak.proxy.helper";
|
||||
|
||||
/// The Apple Developer Team that signs Yaak Proxy, set at build time with
|
||||
/// `YAAK_PROXY_TEAM_ID`.
|
||||
pub const TEAM_ID: &str = match option_env!("YAAK_PROXY_TEAM_ID") {
|
||||
Some(team) => team,
|
||||
None => "7PU3P6ELJ8",
|
||||
};
|
||||
|
||||
/// The bundle identifiers of the apps served: the release app, and the dev app as well in a
|
||||
/// debug build of the helper.
|
||||
pub const APP_IDENTIFIERS: &[&str] = if cfg!(debug_assertions) {
|
||||
&["app.yaak.proxy", "app.yaak.proxy.dev"]
|
||||
} else {
|
||||
&["app.yaak.proxy"]
|
||||
};
|
||||
|
||||
/// The code requirement a caller must satisfy.
|
||||
pub fn code_requirement() -> String {
|
||||
let identifiers = APP_IDENTIFIERS
|
||||
.iter()
|
||||
.map(|id| format!("identifier \"{id}\""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" or ");
|
||||
format!(
|
||||
"anchor apple generic and ({identifiers}) and certificate leaf[subject.OU] = \"{TEAM_ID}\""
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn requires_the_app_signed_by_the_team() {
|
||||
let requirement = code_requirement();
|
||||
assert!(requirement.starts_with("anchor apple generic and (identifier \"app.yaak.proxy\""));
|
||||
assert!(requirement.ends_with(&format!("certificate leaf[subject.OU] = \"{TEAM_ID}\"")));
|
||||
assert_eq!(TEAM_ID.len(), 10);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() {
|
||||
std::process::exit(yaak_proxy_helper::daemon::run());
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn main() {
|
||||
eprintln!("yaak-proxy-helper only runs on macOS");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -0,0 +1,944 @@
|
||||
//! The macOS system proxy as `networksetup` sees it: the web and secure web proxies of each
|
||||
//! network service. Reading needs no rights; changing needs an administrator, which the
|
||||
//! daemon is and the app's password-dialog fallback borrows.
|
||||
//!
|
||||
//! Before pointing the services at `127.0.0.1:<port>`, their settings are saved in a
|
||||
//! [`Snapshot`]; turning off puts back exactly what was there, not just "off".
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const NETWORKSETUP: &str = "/usr/sbin/networksetup";
|
||||
|
||||
/// Where the system proxy is always pointed. Never anywhere else, so a compromised caller can
|
||||
/// at worst send this Mac's traffic to localhost.
|
||||
pub const HOST: &str = "127.0.0.1";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(export_to = "gen_rpc.ts"))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServiceProxy {
|
||||
/// The network service, as System Settings names it: "Wi-Fi", "USB 10/100/1000 LAN".
|
||||
pub name: String,
|
||||
/// What stays the same when the service is renamed: its device ("en0"), or its hardware
|
||||
/// port when it has none. Absent when `networksetup` lists neither.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[cfg_attr(feature = "ts", ts(optional))]
|
||||
pub id: Option<String>,
|
||||
pub http: ProxySetting,
|
||||
pub https: ProxySetting,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(export_to = "gen_rpc.ts"))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProxySetting {
|
||||
pub enabled: bool,
|
||||
pub server: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
impl ProxySetting {
|
||||
pub fn points_at(&self, port: u16) -> bool {
|
||||
self.enabled && self.server == HOST && self.port == port
|
||||
}
|
||||
|
||||
/// This setting as the user's own: one pointing at one of `ports` is ours, left behind, so
|
||||
/// it is saved as off.
|
||||
fn owned(&self, ports: &[u16]) -> Self {
|
||||
let ours = ports.iter().any(|p| self.points_at(*p));
|
||||
Self { enabled: self.enabled && !ours, ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl ServiceProxy {
|
||||
/// A service known by its name only.
|
||||
pub fn new(name: &str, http: ProxySetting, https: ProxySetting) -> Self {
|
||||
Self { name: name.into(), id: None, http, https }
|
||||
}
|
||||
|
||||
/// Either proxy of the service sends traffic to `127.0.0.1:<port>`.
|
||||
pub fn points_at(&self, port: u16) -> bool {
|
||||
self.http.points_at(port) || self.https.points_at(port)
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings of the services the system proxy changed, as they were before, and the port
|
||||
/// it points them at.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Snapshot {
|
||||
pub port: u16,
|
||||
/// Ports it pointed at before moving to `port`, where a service it could not move, or a
|
||||
/// disabled one, may still point.
|
||||
#[serde(default)]
|
||||
pub previous_ports: Vec<u16>,
|
||||
pub services: Vec<ServiceProxy>,
|
||||
/// Proxies a restore has started putting the saved server back on, as `(saved service,
|
||||
/// "http" or "https")`, keyed by the saved entry's name, which a rename doesn't change.
|
||||
/// Setting a server turns the proxy on, so one of these found on with its saved server,
|
||||
/// saved as off, is a restore that stopped halfway.
|
||||
#[serde(default)]
|
||||
pub restoring: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Records the restores `commands` start over `services`, saved before running them.
|
||||
pub fn mark_restoring(&mut self, commands: &[Vec<String>], services: &[ServiceProxy]) {
|
||||
let mut started = Vec::new();
|
||||
for args in commands {
|
||||
let proto = match args.first().map(String::as_str) {
|
||||
Some("-setwebproxy") => "http",
|
||||
Some("-setsecurewebproxy") => "https",
|
||||
_ => continue,
|
||||
};
|
||||
let Some(name) = args.get(1) else { continue };
|
||||
let saved = services
|
||||
.iter()
|
||||
.find(|s| &s.name == name)
|
||||
.and_then(|s| self.get(s, services))
|
||||
.map_or_else(|| name.clone(), |saved| saved.name.clone());
|
||||
started.push((saved, proto.to_string()));
|
||||
}
|
||||
for entry in started {
|
||||
if !self.restoring.contains(&entry) {
|
||||
self.restoring.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_restoring(&self, name: &str, proto: &str) -> bool {
|
||||
self.restoring.iter().any(|(n, p)| n == name && p == proto)
|
||||
}
|
||||
|
||||
pub fn capture(services: &[ServiceProxy], port: u16) -> Self {
|
||||
let mut snapshot = Self::default();
|
||||
snapshot.extend(services, port);
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// Records `services` not saved yet, a network connected since the first capture, and
|
||||
/// moves the snapshot to `port`. Those already saved keep the user's settings, not ours.
|
||||
pub fn extend(&mut self, services: &[ServiceProxy], port: u16) {
|
||||
if self.port != 0 && self.port != port && !self.previous_ports.contains(&self.port) {
|
||||
self.previous_ports.push(self.port);
|
||||
}
|
||||
self.previous_ports.retain(|p| *p != port);
|
||||
self.port = port;
|
||||
let ports = self.ports();
|
||||
// Judged against the snapshot as it was, so an entry added here can't change how the
|
||||
// services after it match.
|
||||
let new: Vec<ServiceProxy> = services
|
||||
.iter()
|
||||
.filter(|service| self.get(service, services).is_none())
|
||||
.map(|service| ServiceProxy {
|
||||
name: service.name.clone(),
|
||||
id: service.id.clone(),
|
||||
http: service.http.owned(&ports),
|
||||
https: service.https.owned(&ports),
|
||||
})
|
||||
.collect();
|
||||
self.services.extend(new);
|
||||
}
|
||||
|
||||
/// Every port this snapshot has pointed services at, the current one first.
|
||||
pub fn ports(&self) -> Vec<u16> {
|
||||
std::iter::once(self.port).chain(self.previous_ports.iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// What was saved for `service`, one of `services`, the network's services now: the entry
|
||||
/// with its name, when the ids don't disagree, or, for a service renamed since, the entry
|
||||
/// on its device whose name no service has any more. Services can share a device, so the
|
||||
/// device decides only when it is unambiguous both ways: one such saved entry, and one
|
||||
/// service on the device with no saved entry by name. Otherwise nothing matches, and the
|
||||
/// saved entry is parked rather than given to the wrong service.
|
||||
fn get(&self, service: &ServiceProxy, services: &[ServiceProxy]) -> Option<&ServiceProxy> {
|
||||
let ids_agree =
|
||||
|s: &ServiceProxy| s.id.is_none() || service.id.is_none() || s.id == service.id;
|
||||
if let Some(saved) = self.services.iter().find(|s| s.name == service.name && ids_agree(s)) {
|
||||
return Some(saved);
|
||||
}
|
||||
let id = service.id.as_ref()?;
|
||||
let mut orphans = self
|
||||
.services
|
||||
.iter()
|
||||
.filter(|s| s.id.as_ref() == Some(id) && !services.iter().any(|c| c.name == s.name));
|
||||
let saved = orphans.next()?;
|
||||
let unclaimed = services
|
||||
.iter()
|
||||
.filter(|c| {
|
||||
c.id.as_ref() == Some(id) && !self.services.iter().any(|s| s.name == c.name)
|
||||
})
|
||||
.count();
|
||||
(orphans.next().is_none() && unclaimed == 1).then_some(saved)
|
||||
}
|
||||
|
||||
/// What is left once this snapshot is restored over `services`: the saved entries none of
|
||||
/// them matched, a service removed or unplugged, kept so its settings are not lost. They
|
||||
/// are parked at port 0, which routes nothing.
|
||||
pub fn leftover(&self, services: &[ServiceProxy]) -> Option<Snapshot> {
|
||||
let unmatched: Vec<ServiceProxy> = self
|
||||
.services
|
||||
.iter()
|
||||
.filter(|saved| {
|
||||
!services
|
||||
.iter()
|
||||
.any(|s| self.get(s, services).is_some_and(|m| std::ptr::eq(m, *saved)))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if unmatched.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Snapshot { services: unmatched, ..Snapshot::default() })
|
||||
}
|
||||
}
|
||||
|
||||
/// The calls that turn the system proxy off at `port`, and whether `snapshot` is used up by
|
||||
/// them. At the snapshot's current port, or at port 0 meaning wherever it is, they put back
|
||||
/// everything it saved. At any other port they put back only what points there, leaving the
|
||||
/// snapshot to the routing still live on its own port.
|
||||
pub fn disable_commands(
|
||||
services: &[ServiceProxy],
|
||||
snapshot: Option<&Snapshot>,
|
||||
port: u16,
|
||||
) -> (Vec<Vec<String>>, bool) {
|
||||
match snapshot {
|
||||
Some(snapshot) if port == 0 || port == snapshot.port => {
|
||||
let mut ports = snapshot.ports();
|
||||
if port != 0 && !ports.contains(&port) {
|
||||
ports.push(port);
|
||||
}
|
||||
(restore_commands(services, Some(snapshot), &ports), true)
|
||||
}
|
||||
Some(snapshot) => (restore_commands(services, Some(snapshot), &[port]), false),
|
||||
None if port == 0 => (Vec::new(), true),
|
||||
None => (restore_commands(services, None, &[port]), true),
|
||||
}
|
||||
}
|
||||
|
||||
/// The services from `networksetup -listallnetworkservices`, the disabled ones too with
|
||||
/// `include_disabled`. The first line is a legend; a leading `*` marks a disabled service.
|
||||
pub fn parse_services(output: &str, include_disabled: bool) -> Vec<String> {
|
||||
output
|
||||
.lines()
|
||||
.skip(1)
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && (include_disabled || !l.starts_with('*')))
|
||||
.map(|l| l.trim_start_matches('*').to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each service's id from `networksetup -listnetworkserviceorder`, as `(name, id)`: its device,
|
||||
/// or `port:<hardware port>` when it has no device, as a VPN may not.
|
||||
pub fn parse_service_ids(output: &str) -> Vec<(String, String)> {
|
||||
let mut ids = Vec::new();
|
||||
let mut name = None;
|
||||
for line in output.lines().map(str::trim) {
|
||||
if let Some(rest) = line.strip_prefix("(Hardware Port:") {
|
||||
let Some(name) = name.take() else { continue };
|
||||
let rest = rest.trim_end_matches(')');
|
||||
let (port, device) = rest.split_once(", Device:").unwrap_or((rest, ""));
|
||||
let (port, device) = (port.trim(), device.trim());
|
||||
if !device.is_empty() {
|
||||
ids.push((name, device.to_string()));
|
||||
} else if !port.is_empty() {
|
||||
ids.push((name, format!("port:{port}")));
|
||||
}
|
||||
} else if line.starts_with('(')
|
||||
&& let Some((_, rest)) = line.split_once(") ")
|
||||
{
|
||||
// "(1) Wi-Fi", or "(*) Name" for a disabled service.
|
||||
name = Some(rest.to_string());
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The output of `networksetup -getwebproxy` or `-getsecurewebproxy`.
|
||||
pub fn parse_proxy(output: &str) -> ProxySetting {
|
||||
let mut setting = ProxySetting::default();
|
||||
for line in output.lines() {
|
||||
let Some((key, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let value = value.trim();
|
||||
match key.trim() {
|
||||
"Enabled" => setting.enabled = value.eq_ignore_ascii_case("yes"),
|
||||
"Server" => setting.server = value.to_string(),
|
||||
"Port" => setting.port = value.parse().unwrap_or_default(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
setting
|
||||
}
|
||||
|
||||
const WEB: [(&str, &str); 2] = [
|
||||
("-setwebproxy", "-setwebproxystate"),
|
||||
("-setsecurewebproxy", "-setsecurewebproxystate"),
|
||||
];
|
||||
|
||||
/// The `networksetup` calls that point every one of `services` at `127.0.0.1:<port>`.
|
||||
pub fn enable_commands(services: &[ServiceProxy], port: u16) -> Vec<Vec<String>> {
|
||||
let mut commands = Vec::new();
|
||||
for service in services {
|
||||
for (set, state) in WEB {
|
||||
let name = service.name.clone();
|
||||
commands.push(vec![set.into(), name.clone(), HOST.into(), port.to_string()]);
|
||||
commands.push(vec![state.into(), name, "on".into()]);
|
||||
}
|
||||
}
|
||||
commands
|
||||
}
|
||||
|
||||
/// The `networksetup` calls that put back what `snapshot` saved for each proxy of `services`
|
||||
/// still pointing at one of `ports`, and turn off those it has nothing saved for. A proxy the
|
||||
/// user has pointed elsewhere since is theirs, and left alone.
|
||||
pub fn restore_commands(
|
||||
services: &[ServiceProxy],
|
||||
snapshot: Option<&Snapshot>,
|
||||
ports: &[u16],
|
||||
) -> Vec<Vec<String>> {
|
||||
let mut commands = Vec::new();
|
||||
for service in services {
|
||||
let saved_service = snapshot.and_then(|s| s.get(service, services));
|
||||
let proxies = [
|
||||
(&service.http, saved_service.map(|s| &s.http)),
|
||||
(&service.https, saved_service.map(|s| &s.https)),
|
||||
];
|
||||
for (((current, saved), (set, state)), proto) in
|
||||
proxies.into_iter().zip(WEB).zip(["http", "https"])
|
||||
{
|
||||
let name = service.name.clone();
|
||||
// An earlier restore set the user's server, which turned it on, and stopped
|
||||
// before turning it back off. Marked by the saved entry, so a rename since
|
||||
// doesn't hide it.
|
||||
let restoring = saved_service
|
||||
.zip(snapshot)
|
||||
.is_some_and(|(saved, snapshot)| snapshot.is_restoring(&saved.name, proto));
|
||||
let unfinished = saved.is_some_and(|s| {
|
||||
!s.enabled
|
||||
&& current.enabled
|
||||
&& current.server == s.server
|
||||
&& current.port == s.port
|
||||
&& restoring
|
||||
});
|
||||
if unfinished {
|
||||
commands.push(vec![state.into(), name, "off".into()]);
|
||||
continue;
|
||||
}
|
||||
if !ports.iter().any(|p| current.points_at(*p)) {
|
||||
continue;
|
||||
}
|
||||
match saved {
|
||||
// Setting the server turns the proxy on, so its state follows.
|
||||
Some(saved) if !saved.server.is_empty() && saved.port != 0 => {
|
||||
let port = saved.port.to_string();
|
||||
commands.push(vec![set.into(), name.clone(), saved.server.clone(), port]);
|
||||
commands.push(vec![state.into(), name, on_off(saved.enabled)]);
|
||||
}
|
||||
_ => commands.push(vec![state.into(), name, "off".into()]),
|
||||
}
|
||||
}
|
||||
}
|
||||
commands
|
||||
}
|
||||
|
||||
fn on_off(on: bool) -> String {
|
||||
if on { "on" } else { "off" }.to_string()
|
||||
}
|
||||
|
||||
/// Runs `networksetup`, real or stubbed.
|
||||
pub trait Networksetup {
|
||||
/// Runs it with `args`, returning what it printed.
|
||||
fn run(&self, args: &[String]) -> Result<String, String>;
|
||||
}
|
||||
|
||||
/// `/usr/sbin/networksetup` itself.
|
||||
pub struct SystemNetworksetup;
|
||||
|
||||
impl Networksetup for SystemNetworksetup {
|
||||
fn run(&self, args: &[String]) -> Result<String, String> {
|
||||
let output = std::process::Command::new(NETWORKSETUP)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run {NETWORKSETUP}: {e}"))?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(if stderr.is_empty() {
|
||||
format!("{NETWORKSETUP} exited with {}", output.status)
|
||||
} else {
|
||||
stderr
|
||||
});
|
||||
}
|
||||
// It reports some failures, such as an unknown service, on stdout with status 0.
|
||||
if stdout.starts_with("** Error") {
|
||||
return Err(stdout.trim().to_string());
|
||||
}
|
||||
Ok(stdout)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every service and its proxies, the disabled ones too with `include_disabled`.
|
||||
pub fn read_services(
|
||||
ns: &impl Networksetup,
|
||||
include_disabled: bool,
|
||||
) -> Result<Vec<ServiceProxy>, String> {
|
||||
let list = ns.run(&["-listallnetworkservices".to_string()])?;
|
||||
// Without ids, services are still matched by name.
|
||||
let ids = ns
|
||||
.run(&["-listnetworkserviceorder".to_string()])
|
||||
.map(|order| parse_service_ids(&order))
|
||||
.unwrap_or_default();
|
||||
parse_services(&list, include_disabled)
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let http = parse_proxy(&ns.run(&["-getwebproxy".into(), name.clone()])?);
|
||||
let https = parse_proxy(&ns.run(&["-getsecurewebproxy".into(), name.clone()])?);
|
||||
let id = ids.iter().find(|(n, _)| *n == name).map(|(_, id)| id.clone());
|
||||
Ok(ServiceProxy { name, id, http, https })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs `commands` in order, stopping at the first that fails.
|
||||
pub fn apply(ns: &impl Networksetup, commands: &[Vec<String>]) -> Result<(), String> {
|
||||
for args in commands {
|
||||
ns.run(args)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A `networksetup` that keeps its services in memory, for tests here and in the app.
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub mod fake {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FakeService {
|
||||
pub proxy: ServiceProxy,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FakeNetworksetup {
|
||||
pub services: Mutex<Vec<FakeService>>,
|
||||
/// Every change made, in order.
|
||||
pub changes: Mutex<Vec<Vec<String>>>,
|
||||
/// A service whose changes fail, as one removed mid-change would.
|
||||
pub failing: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
impl FakeNetworksetup {
|
||||
/// Services on devices `en0`, `en1` and on, in order.
|
||||
pub fn new(services: Vec<(&str, ProxySetting, ProxySetting)>) -> Self {
|
||||
let services = services
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, http, https))| FakeService {
|
||||
proxy: ServiceProxy {
|
||||
name: name.into(),
|
||||
id: Some(format!("en{i}")),
|
||||
http,
|
||||
https,
|
||||
},
|
||||
enabled: true,
|
||||
})
|
||||
.collect();
|
||||
Self { services: Mutex::new(services), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Renames a service, as System Settings can; its device stays.
|
||||
pub fn rename(&self, name: &str, to: &str) {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
services.iter_mut().find(|s| s.proxy.name == name).unwrap().proxy.name = to.into();
|
||||
}
|
||||
|
||||
/// Moves a service onto `device`, which another can share, as a duplicated one does.
|
||||
pub fn set_device(&self, name: &str, device: &str) {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
services.iter_mut().find(|s| s.proxy.name == name).unwrap().proxy.id =
|
||||
Some(device.into());
|
||||
}
|
||||
|
||||
/// Adds an enabled service on `device`.
|
||||
pub fn add(&self, name: &str, device: &str, http: ProxySetting, https: ProxySetting) {
|
||||
let mut proxy = ServiceProxy::new(name, http, https);
|
||||
proxy.id = Some(device.into());
|
||||
self.services.lock().unwrap().push(FakeService { proxy, enabled: true });
|
||||
}
|
||||
|
||||
/// Removes a service, as unplugging an adapter can.
|
||||
pub fn remove(&self, name: &str) {
|
||||
self.services.lock().unwrap().retain(|s| s.proxy.name != name);
|
||||
}
|
||||
|
||||
/// The services' proxies, disabled ones included.
|
||||
pub fn proxies(&self) -> Vec<ServiceProxy> {
|
||||
self.services.lock().unwrap().iter().map(|s| s.proxy.clone()).collect()
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, name: &str, enabled: bool) {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
services.iter_mut().find(|s| s.proxy.name == name).unwrap().enabled = enabled;
|
||||
}
|
||||
|
||||
pub fn set_proxy(&self, name: &str, http: ProxySetting, https: ProxySetting) {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
let service = services.iter_mut().find(|s| s.proxy.name == name).unwrap();
|
||||
service.proxy.http = http;
|
||||
service.proxy.https = https;
|
||||
}
|
||||
}
|
||||
|
||||
impl Networksetup for FakeNetworksetup {
|
||||
fn run(&self, args: &[String]) -> Result<String, String> {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
if args.first().map(String::as_str) == Some("-listallnetworkservices") {
|
||||
let mut out =
|
||||
"An asterisk (*) denotes that a network service is disabled.\n".to_string();
|
||||
for s in services.iter() {
|
||||
out.push_str(&format!(
|
||||
"{}{}\n",
|
||||
if s.enabled { "" } else { "*" },
|
||||
s.proxy.name
|
||||
));
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
if args.first().map(String::as_str) == Some("-listnetworkserviceorder") {
|
||||
let mut out =
|
||||
"An asterisk (*) denotes that a network service is disabled.\n".to_string();
|
||||
for (i, s) in services.iter().enumerate() {
|
||||
let order = if s.enabled { (i + 1).to_string() } else { "*".into() };
|
||||
let device = s.proxy.id.clone().unwrap_or_default();
|
||||
out.push_str(&format!(
|
||||
"({order}) {}\n(Hardware Port: {}, Device: {device})\n\n",
|
||||
s.proxy.name, s.proxy.name
|
||||
));
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let [command, name, rest @ ..] = args else {
|
||||
return Err(format!("bad arguments {args:?}"));
|
||||
};
|
||||
let service = services
|
||||
.iter_mut()
|
||||
.find(|s| &s.proxy.name == name)
|
||||
.ok_or_else(|| format!("** Error: {name} is not a recognized network service."))?;
|
||||
let setting = if command.contains("secure") {
|
||||
&mut service.proxy.https
|
||||
} else {
|
||||
&mut service.proxy.http
|
||||
};
|
||||
match (command.as_str(), rest) {
|
||||
("-getwebproxy" | "-getsecurewebproxy", []) => {
|
||||
return Ok(format!(
|
||||
"Enabled: {}\nServer: {}\nPort: {}\nAuthenticated Proxy Enabled: 0\n",
|
||||
if setting.enabled { "Yes" } else { "No" },
|
||||
setting.server,
|
||||
setting.port
|
||||
));
|
||||
}
|
||||
(_, [_, ..]) if self.failing.lock().unwrap().as_ref() == Some(name) => {
|
||||
return Err(format!("** Error: {name} is not a recognized network service."));
|
||||
}
|
||||
("-setwebproxy" | "-setsecurewebproxy", [server, port]) => {
|
||||
setting.server = server.clone();
|
||||
setting.port = port.parse().map_err(|_| format!("bad port {port}"))?;
|
||||
setting.enabled = true;
|
||||
}
|
||||
("-setwebproxystate" | "-setsecurewebproxystate", [state]) => {
|
||||
setting.enabled = state == "on";
|
||||
}
|
||||
_ => return Err(format!("bad arguments {args:?}")),
|
||||
}
|
||||
self.changes.lock().unwrap().push(args.to_vec());
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::fake::FakeNetworksetup;
|
||||
use super::*;
|
||||
|
||||
fn setting(enabled: bool, server: &str, port: u16) -> ProxySetting {
|
||||
ProxySetting { enabled, server: server.into(), port }
|
||||
}
|
||||
|
||||
fn ours(port: u16) -> ProxySetting {
|
||||
setting(true, HOST, port)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_services() {
|
||||
let output = "An asterisk (*) denotes that a network service is disabled.\nWi-Fi\n*Thunderbolt Bridge\nUSB 10/100/1000 LAN\n\n";
|
||||
assert_eq!(parse_services(output, false), vec!["Wi-Fi", "USB 10/100/1000 LAN"]);
|
||||
// A disabled service can still hold a proxy setting pointing at us.
|
||||
assert_eq!(
|
||||
parse_services(output, true),
|
||||
vec!["Wi-Fi", "Thunderbolt Bridge", "USB 10/100/1000 LAN"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_proxy() {
|
||||
let on = "Enabled: Yes\nServer: 127.0.0.1\nPort: 9090\nAuthenticated Proxy Enabled: 0\n";
|
||||
assert_eq!(parse_proxy(on), ours(9090));
|
||||
let off = "Enabled: No\nServer: \nPort: 0\nAuthenticated Proxy Enabled: 0\n";
|
||||
assert_eq!(parse_proxy(off), setting(false, "", 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_service_ids() {
|
||||
let output = "An asterisk (*) denotes that a network service is disabled.\n(1) Wi-Fi\n(Hardware Port: Wi-Fi, Device: en0)\n\n(*) Thunderbolt Bridge\n(Hardware Port: Thunderbolt Bridge, Device: bridge0)\n\n(3) Tailscale\n(Hardware Port: io.tailscale.ipn.macsys, Device: )\n\n";
|
||||
assert_eq!(
|
||||
parse_service_ids(output),
|
||||
vec![
|
||||
("Wi-Fi".to_string(), "en0".to_string()),
|
||||
("Thunderbolt Bridge".to_string(), "bridge0".to_string()),
|
||||
("Tailscale".to_string(), "port:io.tailscale.ipn.macsys".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_service_renamed_while_routing_gets_its_settings_back() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let ns = FakeNetworksetup::new(vec![("Wi-Fi", corp.clone(), corp.clone())]);
|
||||
let snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
assert_eq!(snapshot.services[0].id.as_deref(), Some("en0"));
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
|
||||
ns.rename("Wi-Fi", "Office Wi-Fi");
|
||||
let services = read_services(&ns, true).unwrap();
|
||||
let (commands, used_up) = disable_commands(&services, Some(&snapshot), 9090);
|
||||
apply(&ns, &commands).unwrap();
|
||||
assert_eq!(ns.proxies()[0].http, corp);
|
||||
assert_eq!(ns.proxies()[0].https, corp);
|
||||
assert!(used_up && snapshot.leftover(&services).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn services_sharing_a_device_keep_their_own_settings() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let lab = setting(true, "lab-proxy", 8888);
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", corp.clone(), corp.clone()),
|
||||
("Wi-Fi Lab", lab.clone(), lab.clone()),
|
||||
]);
|
||||
ns.set_device("Wi-Fi Lab", "en0");
|
||||
let before = ns.proxies();
|
||||
let snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
assert_eq!(snapshot.services.len(), 2);
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
|
||||
let services = read_services(&ns, true).unwrap();
|
||||
let (commands, _) = disable_commands(&services, Some(&snapshot), 9090);
|
||||
apply(&ns, &commands).unwrap();
|
||||
assert_eq!(ns.proxies(), before);
|
||||
assert!(snapshot.leftover(&services).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_plus_a_new_service_on_its_device_matches_neither() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let lab = setting(true, "lab-proxy", 8888);
|
||||
let ns = FakeNetworksetup::new(vec![("Wi-Fi", corp.clone(), corp.clone())]);
|
||||
let mut snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
// While routing: Wi-Fi is renamed, and a second service is added on its device.
|
||||
ns.rename("Wi-Fi", "Office");
|
||||
ns.add("Lab", "en0", lab.clone(), lab.clone());
|
||||
|
||||
// Turned on again: Lab's own settings are saved, not skipped as Wi-Fi's.
|
||||
let services = read_services(&ns, false).unwrap();
|
||||
snapshot.extend(&services, 9090);
|
||||
assert!(snapshot.services.iter().any(|s| s.name == "Lab" && s.http == lab));
|
||||
apply(&ns, &enable_commands(&services, 9090)).unwrap();
|
||||
|
||||
let services = read_services(&ns, true).unwrap();
|
||||
let (commands, _) = disable_commands(&services, Some(&snapshot), 9090);
|
||||
apply(&ns, &commands).unwrap();
|
||||
let proxies = ns.proxies();
|
||||
assert_eq!(proxies[1].http, lab, "Lab gets its own settings back");
|
||||
assert!(!proxies[0].points_at(9090));
|
||||
assert_ne!(proxies[0].http, corp, "ambiguous, so Office is not handed Wi-Fi's");
|
||||
// Wi-Fi's saved settings are not lost.
|
||||
let leftover = snapshot.leftover(&services).unwrap();
|
||||
assert!(leftover.services.iter().any(|s| s.name == "Wi-Fi" && s.http == corp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_beside_a_duplicate_still_matches() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let lab = setting(true, "lab-proxy", 8888);
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", corp.clone(), corp.clone()),
|
||||
("Wi-Fi Lab", lab.clone(), lab.clone()),
|
||||
]);
|
||||
ns.set_device("Wi-Fi Lab", "en0");
|
||||
let snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
ns.rename("Wi-Fi", "Office");
|
||||
|
||||
let services = read_services(&ns, true).unwrap();
|
||||
let (commands, _) = disable_commands(&services, Some(&snapshot), 9090);
|
||||
apply(&ns, &commands).unwrap();
|
||||
assert_eq!(ns.proxies()[0].http, corp);
|
||||
assert_eq!(ns.proxies()[1].http, lab);
|
||||
assert!(snapshot.leftover(&services).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_entry_no_service_matches_is_kept() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", corp.clone(), corp.clone()),
|
||||
("USB LAN", corp.clone(), corp.clone()),
|
||||
]);
|
||||
let snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
ns.remove("USB LAN");
|
||||
|
||||
let leftover = snapshot.leftover(&read_services(&ns, true).unwrap()).unwrap();
|
||||
assert_eq!(leftover.port, 0);
|
||||
assert_eq!(leftover.services.len(), 1);
|
||||
assert_eq!(leftover.services[0].name, "USB LAN");
|
||||
assert_eq!(leftover.services[0].http, corp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_named_service_on_another_device_is_not_matched() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let mut saved = ServiceProxy::new("Ethernet", corp.clone(), corp);
|
||||
saved.id = Some("en5".into());
|
||||
let snapshot = Snapshot { port: 9090, services: vec![saved], ..Snapshot::default() };
|
||||
let mut other = ServiceProxy::new("Ethernet", setting(true, HOST, 9090), ours(9090));
|
||||
other.id = Some("en6".into());
|
||||
assert_eq!(
|
||||
restore_commands(&[other], Some(&snapshot), &[9090]),
|
||||
vec![
|
||||
vec!["-setwebproxystate", "Ethernet", "off"],
|
||||
vec!["-setsecurewebproxystate", "Ethernet", "off"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_points_every_service_at_localhost() {
|
||||
let services = vec![ServiceProxy::new(
|
||||
"Wi-Fi",
|
||||
ProxySetting::default(),
|
||||
ProxySetting::default(),
|
||||
)];
|
||||
assert_eq!(
|
||||
enable_commands(&services, 9090),
|
||||
vec![
|
||||
vec!["-setwebproxy", "Wi-Fi", "127.0.0.1", "9090"],
|
||||
vec!["-setwebproxystate", "Wi-Fi", "on"],
|
||||
vec!["-setsecurewebproxy", "Wi-Fi", "127.0.0.1", "9090"],
|
||||
vec!["-setsecurewebproxystate", "Wi-Fi", "on"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_round_trip_puts_back_exactly_what_was_there() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let parked = setting(false, "old-proxy", 8888);
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", corp.clone(), parked.clone()),
|
||||
("Ethernet", ProxySetting::default(), ProxySetting::default()),
|
||||
]);
|
||||
let before = ns.proxies();
|
||||
|
||||
let services = read_services(&ns, false).unwrap();
|
||||
let snapshot = Snapshot::capture(&services, 9090);
|
||||
apply(&ns, &enable_commands(&services, 9090)).unwrap();
|
||||
assert!(ns.proxies().iter().all(|s| s.http.points_at(9090) && s.https.points_at(9090)));
|
||||
|
||||
let restore =
|
||||
restore_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), &[9090]);
|
||||
apply(&ns, &restore).unwrap();
|
||||
let after = ns.proxies();
|
||||
assert_eq!(after[0], before[0]);
|
||||
// A service that never had a server is turned off, keeping ours as the unused server.
|
||||
assert!(!after[1].http.enabled && !after[1].https.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_leaves_a_proxy_the_user_changed_since() {
|
||||
let ns = FakeNetworksetup::new(vec![(
|
||||
"Wi-Fi",
|
||||
setting(true, "corp-proxy", 3128),
|
||||
setting(true, "corp-proxy", 3128),
|
||||
)]);
|
||||
let services = read_services(&ns, false).unwrap();
|
||||
let snapshot = Snapshot::capture(&services, 9090);
|
||||
apply(&ns, &enable_commands(&services, 9090)).unwrap();
|
||||
// The user points HTTPS somewhere else while ours is on.
|
||||
ns.set_proxy("Wi-Fi", ours(9090), setting(true, "charles", 8888));
|
||||
|
||||
let restore =
|
||||
restore_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), &[9090]);
|
||||
assert_eq!(
|
||||
restore,
|
||||
vec![
|
||||
vec!["-setwebproxy", "Wi-Fi", "corp-proxy", "3128"],
|
||||
vec!["-setwebproxystate", "Wi-Fi", "on"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_without_a_snapshot_turns_off_only_our_proxies() {
|
||||
let services = vec![
|
||||
ServiceProxy::new("Wi-Fi", ours(9090), ours(9090)),
|
||||
// Someone else's proxy, and ours on another port.
|
||||
ServiceProxy::new("Ethernet", setting(true, "corp-proxy", 9090), ours(8080)),
|
||||
];
|
||||
assert!(services[0].points_at(9090) && !services[1].points_at(9090));
|
||||
assert_eq!(
|
||||
restore_commands(&services, None, &[9090]),
|
||||
vec![
|
||||
vec!["-setwebproxystate", "Wi-Fi", "off"],
|
||||
vec!["-setsecurewebproxystate", "Wi-Fi", "off"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capture_over_our_own_leftover_saves_it_as_off() {
|
||||
// A crash left Wi-Fi pointing at us with nothing saved.
|
||||
let services = vec![ServiceProxy::new("Wi-Fi", ours(9090), ours(9090))];
|
||||
let snapshot = Snapshot::capture(&services, 9090);
|
||||
assert!(!snapshot.services[0].http.enabled && !snapshot.services[0].https.enabled);
|
||||
let restore = restore_commands(&services, Some(&snapshot), &[9090]);
|
||||
assert_eq!(
|
||||
restore,
|
||||
vec![
|
||||
vec!["-setwebproxy", "Wi-Fi", "127.0.0.1", "9090"],
|
||||
vec!["-setwebproxystate", "Wi-Fi", "off"],
|
||||
vec!["-setsecurewebproxy", "Wi-Fi", "127.0.0.1", "9090"],
|
||||
vec!["-setsecurewebproxystate", "Wi-Fi", "off"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extending_keeps_the_first_capture_and_adds_new_services() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let mut snapshot =
|
||||
Snapshot::capture(&[ServiceProxy::new("Wi-Fi", corp.clone(), corp.clone())], 9090);
|
||||
// Turned on again on another port: Wi-Fi now shows ours, and Ethernet is new.
|
||||
snapshot.extend(
|
||||
&[
|
||||
ServiceProxy::new("Wi-Fi", ours(9090), ours(9090)),
|
||||
ServiceProxy::new("Ethernet", corp.clone(), corp.clone()),
|
||||
],
|
||||
9191,
|
||||
);
|
||||
assert_eq!(snapshot.port, 9191);
|
||||
assert_eq!(snapshot.services.len(), 2);
|
||||
assert_eq!(snapshot.services[0].http, corp);
|
||||
assert_eq!(snapshot.services[1].https, corp);
|
||||
}
|
||||
|
||||
/// Enables on 9090 over `parked`, then runs only the first call of the restore, as a crash
|
||||
/// would leave it: the saved server is back, but on.
|
||||
fn cut_short(parked: &ProxySetting) -> (FakeNetworksetup, Snapshot) {
|
||||
let ns = FakeNetworksetup::new(vec![("Wi-Fi", parked.clone(), parked.clone())]);
|
||||
let mut snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
let restore =
|
||||
restore_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), &[9090]);
|
||||
snapshot.mark_restoring(&restore, &read_services(&ns, true).unwrap());
|
||||
apply(&ns, &restore[..1]).unwrap();
|
||||
assert!(ns.proxies()[0].http.enabled);
|
||||
(ns, snapshot)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restore_cut_short_is_finished_on_the_next_try() {
|
||||
let parked = setting(false, "old-proxy", 8888);
|
||||
let (ns, snapshot) = cut_short(&parked);
|
||||
let (retry, used_up) =
|
||||
disable_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), 9090);
|
||||
assert!(used_up);
|
||||
apply(&ns, &retry).unwrap();
|
||||
assert_eq!(ns.proxies()[0].http, parked);
|
||||
assert_eq!(ns.proxies()[0].https, parked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_short_restore_is_finished_after_a_rename() {
|
||||
let parked = setting(false, "old-proxy", 8888);
|
||||
let (ns, snapshot) = cut_short(&parked);
|
||||
ns.rename("Wi-Fi", "Office Wi-Fi");
|
||||
let (retry, _) =
|
||||
disable_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), 9090);
|
||||
apply(&ns, &retry).unwrap();
|
||||
assert_eq!(ns.proxies()[0].http, parked);
|
||||
assert_eq!(ns.proxies()[0].https, parked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_short_restore_of_a_localhost_proxy_is_finished_too() {
|
||||
let parked = setting(false, HOST, 8888);
|
||||
let (ns, snapshot) = cut_short(&parked);
|
||||
let (retry, _) =
|
||||
disable_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), 9090);
|
||||
apply(&ns, &retry).unwrap();
|
||||
assert_eq!(ns.proxies()[0].http, parked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_the_user_turned_on_themselves_is_left_on() {
|
||||
let parked = setting(false, "corp-proxy", 3128);
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", ProxySetting::default(), ProxySetting::default()),
|
||||
("Ethernet", parked.clone(), parked.clone()),
|
||||
]);
|
||||
let snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
apply(&ns, &enable_commands(&ns.proxies()[..1], 9090)).unwrap();
|
||||
// A VPN turns the parked corporate proxy on while ours runs on Wi-Fi.
|
||||
let on = setting(true, "corp-proxy", 3128);
|
||||
ns.set_proxy("Ethernet", on.clone(), on.clone());
|
||||
let (commands, _) =
|
||||
disable_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), 9090);
|
||||
apply(&ns, &commands).unwrap();
|
||||
assert_eq!(ns.proxies()[1].http, on);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_an_old_port_puts_back_what_was_saved_there() {
|
||||
let corp = setting(true, "corp-proxy", 3128);
|
||||
let ns = FakeNetworksetup::new(vec![
|
||||
("Wi-Fi", corp.clone(), corp.clone()),
|
||||
("Ethernet", corp.clone(), corp.clone()),
|
||||
]);
|
||||
let mut snapshot = Snapshot::capture(&read_services(&ns, false).unwrap(), 9090);
|
||||
apply(&ns, &enable_commands(&read_services(&ns, false).unwrap(), 9090)).unwrap();
|
||||
// Ethernet is disabled before the move to 9191, so it stays on 9090.
|
||||
ns.set_enabled("Ethernet", false);
|
||||
let enabled = read_services(&ns, false).unwrap();
|
||||
snapshot.extend(&enabled, 9191);
|
||||
apply(&ns, &enable_commands(&enabled, 9191)).unwrap();
|
||||
|
||||
let (commands, used_up) =
|
||||
disable_commands(&read_services(&ns, true).unwrap(), Some(&snapshot), 9090);
|
||||
assert!(!used_up);
|
||||
apply(&ns, &commands).unwrap();
|
||||
assert_eq!(ns.proxies()[1].http, corp);
|
||||
assert!(ns.proxies()[0].http.points_at(9191), "live routing kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fake_refuses_an_unknown_service() {
|
||||
let ns = FakeNetworksetup::new(vec![]);
|
||||
assert!(ns.run(&["-getwebproxy".into(), "Nope".into()]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Telling whether the process that turned the system proxy on is still the same process. A
|
||||
//! pid alone is not enough once it can be reused, after a reboot for one, so the owner is the
|
||||
//! pid and the time it started.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Owner {
|
||||
pub pid: i32,
|
||||
/// Microseconds since the epoch.
|
||||
pub started: u64,
|
||||
}
|
||||
|
||||
pub trait Processes {
|
||||
/// When `pid` started, while it runs.
|
||||
fn start_time(&self, pid: i32) -> Option<u64>;
|
||||
|
||||
fn owner(&self, pid: i32) -> Option<Owner> {
|
||||
Some(Owner { pid, started: self.start_time(pid)? })
|
||||
}
|
||||
|
||||
fn is_alive(&self, owner: &Owner) -> bool {
|
||||
self.start_time(owner.pid) == Some(owner.started)
|
||||
}
|
||||
}
|
||||
|
||||
/// This Mac's processes, through `proc_pidinfo`.
|
||||
pub struct SystemProcesses;
|
||||
|
||||
impl Processes for SystemProcesses {
|
||||
fn start_time(&self, pid: i32) -> Option<u64> {
|
||||
if pid <= 0 {
|
||||
return None;
|
||||
}
|
||||
let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::zeroed();
|
||||
let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
|
||||
// SAFETY: `info` is a buffer of exactly `size` bytes for PROC_PIDTBSDINFO to fill.
|
||||
let written = unsafe {
|
||||
libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, info.as_mut_ptr().cast(), size)
|
||||
};
|
||||
if written != size {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: proc_pidinfo filled the whole struct.
|
||||
let info = unsafe { info.assume_init() };
|
||||
// A zombie has exited; only its parent has yet to notice.
|
||||
if info.pbi_status == libc::SZOMB {
|
||||
return None;
|
||||
}
|
||||
Some(info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn knows_this_process_and_not_a_missing_one() {
|
||||
let me = SystemProcesses.owner(std::process::id() as i32).unwrap();
|
||||
assert!(SystemProcesses.is_alive(&me));
|
||||
// Same pid, different start: the pid was reused.
|
||||
assert!(!SystemProcesses.is_alive(&Owner { started: me.started + 1, ..me }));
|
||||
assert_eq!(SystemProcesses.start_time(0), None);
|
||||
assert_eq!(SystemProcesses.start_time(i32::MAX), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_that_exited_is_not_alive() {
|
||||
let mut child = std::process::Command::new("/usr/bin/true").spawn().unwrap();
|
||||
let owner = SystemProcesses.owner(child.id() as i32);
|
||||
child.wait().unwrap();
|
||||
if let Some(owner) = owner {
|
||||
assert!(!SystemProcesses.is_alive(&owner));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! What the app and the daemon say to each other: one JSON object per line each way, a
|
||||
//! [`Request`] and its [`Response`].
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The lowest port the system proxy may point at: never a privileged one.
|
||||
pub const MIN_PORT: u16 = 1024;
|
||||
|
||||
/// The longest request line read, far more than any request needs.
|
||||
pub const MAX_LINE: usize = 4096;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "cmd", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Request {
|
||||
/// What the daemon has done to the system proxy.
|
||||
Get,
|
||||
/// Points every enabled service at `127.0.0.1:<port>`, saving the settings it replaces,
|
||||
/// and restores them once `owner_pid` exits. Off restores them now.
|
||||
Set {
|
||||
enabled: bool,
|
||||
port: u16,
|
||||
owner_pid: i32,
|
||||
},
|
||||
/// Puts back the saved settings.
|
||||
Restore,
|
||||
/// Restores and deletes the daemon's state, before the app unregisters it, which stops it.
|
||||
Unregister,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Status {
|
||||
/// The daemon has pointed the system proxy at the engine and will restore it.
|
||||
pub active: bool,
|
||||
pub port: Option<u16>,
|
||||
pub owner_pid: Option<i32>,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Response {
|
||||
pub ok: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub status: Option<Status>,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn ok(status: Status) -> Self {
|
||||
Self { ok: true, error: None, status: Some(status) }
|
||||
}
|
||||
|
||||
pub fn error(message: impl Into<String>) -> Self {
|
||||
Self { ok: false, error: Some(message.into()), status: None }
|
||||
}
|
||||
|
||||
pub fn into_result(self) -> Result<Status, String> {
|
||||
if self.ok {
|
||||
Ok(self.status.unwrap_or_default())
|
||||
} else {
|
||||
Err(self.error.unwrap_or_else(|| "The helper refused the request".to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and checks one request line. The host is not a field: it is always `127.0.0.1`.
|
||||
pub fn parse_request(line: &str) -> Result<Request, String> {
|
||||
let request: Request =
|
||||
serde_json::from_str(line.trim()).map_err(|e| format!("Invalid request: {e}"))?;
|
||||
if let Request::Set { enabled: true, port, owner_pid } = request {
|
||||
if port < MIN_PORT {
|
||||
return Err(format!("Port {port} is outside {MIN_PORT} to 65535"));
|
||||
}
|
||||
if owner_pid <= 0 {
|
||||
return Err(format!("Invalid owner pid {owner_pid}"));
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_each_command() {
|
||||
assert_eq!(parse_request(r#"{"cmd":"get"}"#), Ok(Request::Get));
|
||||
assert_eq!(parse_request("{\"cmd\":\"restore\"}\n"), Ok(Request::Restore));
|
||||
assert_eq!(parse_request(r#"{"cmd":"unregister"}"#), Ok(Request::Unregister));
|
||||
assert_eq!(
|
||||
parse_request(r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":42}"#),
|
||||
Ok(Request::Set { enabled: true, port: 9090, owner_pid: 42 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_ports_outside_1024_to_65535() {
|
||||
for port in [0, 80, 1023] {
|
||||
let line = format!(r#"{{"cmd":"set","enabled":true,"port":{port},"owner_pid":42}}"#);
|
||||
assert!(parse_request(&line).is_err(), "port {port}");
|
||||
}
|
||||
assert!(
|
||||
parse_request(r#"{"cmd":"set","enabled":true,"port":65536,"owner_pid":42}"#).is_err()
|
||||
);
|
||||
assert!(parse_request(r#"{"cmd":"set","enabled":true,"port":-1,"owner_pid":42}"#).is_err());
|
||||
assert!(
|
||||
parse_request(r#"{"cmd":"set","enabled":true,"port":1024,"owner_pid":42}"#).is_ok()
|
||||
);
|
||||
assert!(
|
||||
parse_request(r#"{"cmd":"set","enabled":true,"port":65535,"owner_pid":42}"#).is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_host() {
|
||||
let line = r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":42,"host":"10.0.0.1"}"#;
|
||||
assert!(parse_request(line).unwrap_err().contains("host"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bad_owner_and_junk() {
|
||||
assert!(
|
||||
parse_request(r#"{"cmd":"set","enabled":true,"port":9090,"owner_pid":0}"#).is_err()
|
||||
);
|
||||
assert!(parse_request(r#"{"cmd":"set","enabled":true,"port":9090}"#).is_err());
|
||||
assert!(parse_request(r#"{"cmd":"rm -rf"}"#).is_err());
|
||||
assert!(parse_request("not json").is_err());
|
||||
assert!(parse_request("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_off_needs_no_valid_port() {
|
||||
// Off restores whatever the daemon saved; the port only widens what counts as ours.
|
||||
assert!(parse_request(r#"{"cmd":"set","enabled":false,"port":0,"owner_pid":0}"#).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_round_trip() {
|
||||
let ok = Response::ok(Status {
|
||||
active: true,
|
||||
port: Some(9090),
|
||||
owner_pid: Some(1),
|
||||
version: "1".into(),
|
||||
});
|
||||
let line = serde_json::to_string(&ok).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Response>(&line).unwrap(), ok);
|
||||
assert_eq!(Response::error("no").into_result(), Err("no".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ edition = "2024"
|
||||
publish = false
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
dark-light = "2.0.0"
|
||||
dark-light = "3.0.0"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
dispatch2 = "0.3.0"
|
||||
|
||||
@@ -7,7 +7,7 @@ publish = false
|
||||
[dependencies]
|
||||
log = { workspace = true }
|
||||
md5 = "0.8.0"
|
||||
rand = "0.9.0"
|
||||
rand = "0.10.2"
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
|
||||
Reference in new issue
Block a user