Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions crates/sage-apps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ tempfile = "3"
zip = "8.5.1"
mime_guess = "2"
url = "2"
async-trait = "0.1.89"
erased-serde = "0.4.9"
serde_path_to_error = "0.1.20"
parking_lot = "0.12.5"
futures = "0.3.32"
Expand Down
122 changes: 98 additions & 24 deletions crates/sage-apps/src/bridge/bridge_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ use tauri::{AppHandle, Manager, State, Webview};

use crate::{
AppState, AppsHostState, BridgeApprovalsChangedEvent, BridgeCapability, BridgeContext,
BridgeMethod, BridgeMethodCapability, BridgeOrigin, BridgeRegistry, BridgeRegistryKind,
BridgeMethodCapability, BridgeMethodEntry, BridgeOrigin, BridgeRegistry, BridgeRegistryKind,
BridgeTools, ResolveBridgeApprovalArgs, RustBridgeApprovalRequest, RustBridgeInvokeResult,
RustBridgeRequest, RustBridgeResponse, SharedSageApp, SystemBridgeCapability,
UserBridgeCapability, assert_bridge_origin, emit_bridge_response_to_app,
emit_system_runtime_event_to_listeners, ensure_app_is_enabled_for_scope,
ensure_approval_expiry_loop, get_pending_approval, get_system_capability_definition,
get_user_capability_definition, list_pending_approvals, remove_pending_approval, resolve_app,
start_bridge_approval_runtime, sync_bridge_approval_runtime, write_pending_approval,
UserBridgeCapability, UserBridgeMethodEntry, UserBridgeRegistry, assert_bridge_origin,
emit_bridge_response_to_app, emit_system_runtime_event_to_listeners,
ensure_app_is_enabled_for_scope, ensure_approval_expiry_loop, get_pending_approval,
get_system_capability_definition, get_user_capability_definition, list_pending_approvals,
remove_pending_approval, resolve_app, start_bridge_approval_runtime,
sync_bridge_approval_runtime, write_pending_approval,
};

pub(crate) async fn process(
Expand Down Expand Up @@ -103,15 +104,12 @@ pub(crate) async fn process_after_approval(
assert_bridge_origin(app_handle, &app.with_app(SharedSageApp::webview_label)).await?;

let invoke_result = if args.approved {
process_shared(
app_handle,
app_state,
&origin,
pending.registry_kind,
&pending.request,
true,
)
.await?
if pending.registry_kind != BridgeRegistryKind::User {
return Err("only user bridge approvals can be resolved".to_string());
}

execute_approved_user_bridge_request(app_handle, app_state, &origin, &pending.request)
.await?
} else {
RustBridgeInvokeResult::error(
&pending.request.id,
Expand All @@ -125,6 +123,44 @@ pub(crate) async fn process_after_approval(
Ok(())
}

async fn execute_approved_user_bridge_request(
app_handle: &AppHandle,
app_state: &State<'_, AppState>,
origin: &BridgeOrigin,
request: &RustBridgeRequest,
) -> Result<RustBridgeInvokeResult, String> {
let registry = UserBridgeRegistry::new();
let app = &origin.app;

if let Err(err) = ensure_app_is_enabled_for_scope(app_state, app).await {
return Ok(RustBridgeInvokeResult::error(
&request.id,
"app_not_enabled_for_scope",
err,
));
}

let method = match assert_user_method(&registry, request) {
Ok(method) => method,
Err(response) => return Ok(response.into()),
};

match method.capability() {
BridgeMethodCapability::Ungated => {}
BridgeMethodCapability::Required(capability) => {
if let Err(response) = verify_capability(&origin.app, request, capability) {
return Ok(response.into());
}
}
}

Ok(
execute_user_bridge_request(app_handle, app_state, origin, registry, request)
.await
.into(),
)
}

async fn process_shared(
app_handle: &AppHandle,
app_state: &State<'_, AppState>,
Expand Down Expand Up @@ -210,14 +246,37 @@ async fn execute_bridge_request(
.await;

match result {
Ok(value) => match erased_serde::serialize(&*value, serde_json::value::Serializer) {
Ok(value) => RustBridgeResponse::success(&request.id, &value),
Err(err) => RustBridgeResponse::error(
&request.id,
"internal_error",
format!("failed to encode {} result: {err}", method.name()),
),
},
Ok(value) => RustBridgeResponse::success(&request.id, &value),
Err(err) => RustBridgeResponse::error(&request.id, err.code, err.message),
}
}

async fn execute_user_bridge_request(
app_handle: &AppHandle,
app_state: &State<'_, AppState>,
origin: &BridgeOrigin,
registry: UserBridgeRegistry,
request: &RustBridgeRequest,
) -> RustBridgeResponse {
let method = match assert_user_method(&registry, request) {
Ok(method) => method,
Err(response) => return response,
};

let result = method
.handle(
BridgeContext { app: &origin.app },
BridgeTools {
app_handle,
app_state,
host_state: &app_handle.state::<AppsHostState>(),
},
request,
)
.await;

match result {
Ok(value) => RustBridgeResponse::success(&request.id, &value),
Err(err) => RustBridgeResponse::error(&request.id, err.code, err.message),
}
}
Expand Down Expand Up @@ -345,7 +404,22 @@ fn verify_system_capability(
fn assert_method<'a>(
registry: &'a BridgeRegistry,
request: &RustBridgeRequest,
) -> Result<&'a dyn BridgeMethod, RustBridgeResponse> {
) -> Result<BridgeMethodEntry<'a>, RustBridgeResponse> {
let Some(method) = registry.get(&request.method) else {
return Err(RustBridgeResponse::error(
&request.id,
"method_not_found",
format!("Unknown bridge method: {}", request.method),
));
};

Ok(method)
}

fn assert_user_method<'a>(
registry: &'a UserBridgeRegistry,
request: &RustBridgeRequest,
) -> Result<&'a UserBridgeMethodEntry, RustBridgeResponse> {
let Some(method) = registry.get(&request.method) else {
return Err(RustBridgeResponse::error(
&request.id,
Expand Down
23 changes: 15 additions & 8 deletions crates/sage-apps/src/bridge/methods/shared.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use async_trait::async_trait;
use std::future::Future;

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::{
AppState, AppsHostState, BridgeCapability, RustBridgeApprovalRequest, RustBridgeRequest,
SharedSageApp, SystemBridgeCapability, UserBridgeCapability,
};

#[async_trait]
pub(crate) trait BridgeMethod: Send + Sync {
pub(crate) trait BridgeMethodHandler: Send + Sync {
fn name(&self) -> &'static str;
fn capability(&self) -> BridgeMethodCapability;

Expand All @@ -17,12 +19,12 @@ pub(crate) trait BridgeMethod: Send + Sync {
request: &RustBridgeRequest,
) -> BridgeApprovalRequestResult;

async fn handle(
fn handle(
&self,
ctx: BridgeContext<'_>,
tools: BridgeTools<'_>,
request: &RustBridgeRequest,
) -> BridgeHandleResult;
) -> impl Future<Output = BridgeHandleResult> + Send;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -69,8 +71,13 @@ impl BridgeMethodHandleError {
}
}

pub(crate) type BridgeHandleResult =
Result<Box<dyn erased_serde::Serialize + Send>, BridgeMethodHandleError>;
pub(crate) type BridgeHandleResult = Result<Value, BridgeMethodHandleError>;

pub(crate) fn bridge_result(value: impl Serialize) -> BridgeHandleResult {
serde_json::to_value(value).map_err(|err| {
BridgeMethodHandleError::internal_error(format!("failed to encode bridge result: {err}"))
})
}

impl BridgeMethodCapability {
pub(super) fn ungated() -> Self {
Expand All @@ -87,7 +94,7 @@ impl BridgeMethodCapability {
}

pub(crate) fn parse_required_params<T>(
method: &impl BridgeMethod,
method: &impl BridgeMethodHandler,
request: &RustBridgeRequest,
) -> Result<T, BridgeMethodHandleError>
where
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::io;

use async_trait::async_trait;
use serde::Deserialize;
use specta::Type;
use tauri::{AppHandle, Manager, State};

use crate::{
AppInstallInstallResult, AppState, AppsHostState, BridgeApprovalRequestResult, BridgeContext,
BridgeHandleResult, BridgeMethod, BridgeMethodCapability, BridgeMethodHandleError, BridgeTools,
Result, RustBridgeRequest, SageAppUrl, SageAppWalletScope, SageGrantedPermissionsInput,
SystemBridgeCapability, UserSageAppView, install_app_from_source, parse_required_params,
BridgeHandleResult, BridgeMethodCapability, BridgeMethodHandleError, BridgeMethodHandler,
BridgeTools, Result, RustBridgeRequest, SageAppUrl, SageAppWalletScope,
SageGrantedPermissionsInput, SystemBridgeCapability, UserSageAppView, bridge_result,
install_app_from_source, parse_required_params,
};

#[derive(Debug, Deserialize, Type)]
Expand All @@ -23,8 +23,7 @@ pub struct AppInstallInstallUrlParams {
#[derive(Debug, Clone, Copy)]
pub(crate) struct AppInstallInstallUrl;

#[async_trait]
impl BridgeMethod for AppInstallInstallUrl {
impl BridgeMethodHandler for AppInstallInstallUrl {
fn name(&self) -> &'static str {
"appInstall.installUrl"
}
Expand Down Expand Up @@ -61,7 +60,7 @@ impl BridgeMethod for AppInstallInstallUrl {
.await
.map_err(|err| BridgeMethodHandleError::internal_error(err.to_string()))?;

Ok(Box::new(AppInstallInstallResult::new(app)))
bridge_result(AppInstallInstallResult::new(app))
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use std::{fs, io};

use async_trait::async_trait;
use serde::Deserialize;
use specta::Type;
use tauri::{AppHandle, Manager, State};

use super::AppInstallInstallResult;
use crate::{
AppState, AppsHostState, BridgeApprovalRequestResult, BridgeContext, BridgeHandleResult,
BridgeMethod, BridgeMethodCapability, BridgeMethodHandleError, BridgeTools, Result,
RustBridgeRequest, SageAppWalletScope, SageGrantedPermissionsInput, SystemBridgeCapability,
UserSageAppView, ZipInstallSource, apps_root, install_app_from_source, parse_required_params,
AppInstallInstallResult, AppState, AppsHostState, BridgeApprovalRequestResult, BridgeContext,
BridgeHandleResult, BridgeMethodCapability, BridgeMethodHandleError, BridgeMethodHandler,
BridgeTools, Result, RustBridgeRequest, SageAppWalletScope, SageGrantedPermissionsInput,
SystemBridgeCapability, UserSageAppView, ZipInstallSource, apps_root, bridge_result,
install_app_from_source, parse_required_params,
};

#[derive(Debug, Deserialize, Type)]
Expand All @@ -24,8 +23,7 @@ pub struct AppInstallInstallZipParams {
#[derive(Debug, Clone, Copy)]
pub(crate) struct AppInstallInstallZip;

#[async_trait]
impl BridgeMethod for AppInstallInstallZip {
impl BridgeMethodHandler for AppInstallInstallZip {
fn name(&self) -> &'static str {
"appInstall.installZip"
}
Expand Down Expand Up @@ -62,7 +60,7 @@ impl BridgeMethod for AppInstallInstallZip {
.await
.map_err(|err| BridgeMethodHandleError::internal_error(err.to_string()))?;

Ok(Box::new(AppInstallInstallResult::new(app)))
bridge_result(AppInstallInstallResult::new(app))
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use async_trait::async_trait;
use serde::Deserialize;
use specta::Type;

use crate::{
BridgeApprovalRequestResult, BridgeContext, BridgeHandleResult, BridgeMethod,
BridgeMethodCapability, BridgeMethodHandleError, BridgeTools, RustBridgeRequest, SageAppUrl,
SageAppUrlPreview, SystemBridgeCapability, fetch_url_manifest_preview, parse_required_params,
BridgeApprovalRequestResult, BridgeContext, BridgeHandleResult, BridgeMethodCapability,
BridgeMethodHandleError, BridgeMethodHandler, BridgeTools, RustBridgeRequest, SageAppUrl,
SageAppUrlPreview, SystemBridgeCapability, bridge_result, fetch_url_manifest_preview,
parse_required_params,
};

#[derive(Debug, Deserialize, Type)]
Expand All @@ -17,8 +17,7 @@ pub struct AppInstallPreviewUrlParams {
#[derive(Debug, Clone, Copy)]
pub(crate) struct AppInstallPreviewUrl;

#[async_trait]
impl BridgeMethod for AppInstallPreviewUrl {
impl BridgeMethodHandler for AppInstallPreviewUrl {
fn name(&self) -> &'static str {
"appInstall.previewUrl"
}
Expand Down Expand Up @@ -47,7 +46,7 @@ impl BridgeMethod for AppInstallPreviewUrl {
.await
.map_err(BridgeMethodHandleError::internal_error)?;

Ok(Box::new(preview))
bridge_result(preview)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use std::fs;
use std::path::Path;

use async_trait::async_trait;
use serde::Deserialize;
use specta::Type;
use uuid::Uuid;

use crate::{
BridgeApprovalRequestResult, BridgeContext, BridgeHandleResult, BridgeMethod,
BridgeMethodCapability, BridgeMethodHandleError, BridgeTools, RustBridgeRequest,
SageAppPackageManifest, SystemBridgeCapability, detect_package_root, parse_required_params,
read_manifest, unzip_to_dir,
BridgeApprovalRequestResult, BridgeContext, BridgeHandleResult, BridgeMethodCapability,
BridgeMethodHandleError, BridgeMethodHandler, BridgeTools, RustBridgeRequest,
SageAppPackageManifest, SystemBridgeCapability, bridge_result, detect_package_root,
parse_required_params, read_manifest, unzip_to_dir,
};

#[derive(Debug, Deserialize, Type)]
Expand All @@ -22,8 +21,7 @@ pub struct AppInstallPreviewZipParams {
#[derive(Debug, Clone, Copy)]
pub(crate) struct AppInstallPreviewZip;

#[async_trait]
impl BridgeMethod for AppInstallPreviewZip {
impl BridgeMethodHandler for AppInstallPreviewZip {
fn name(&self) -> &'static str {
"appInstall.previewZip"
}
Expand Down Expand Up @@ -51,7 +49,7 @@ impl BridgeMethod for AppInstallPreviewZip {
let manifest =
preview_manifest(&params.zip_path).map_err(BridgeMethodHandleError::internal_error)?;

Ok(Box::new(manifest))
bridge_result(manifest)
}
}

Expand Down
Loading
Loading