Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ios): applink verification (#449)

Sean Ayed5d8b1067304
diff --git a/js/app/src-tauri/.gitignore b/js/app/src-tauri/.gitignore
index 502406b4ed..a708de509d 100644
--- a/js/app/src-tauri/.gitignore
+++ b/js/app/src-tauri/.gitignore
@@ -2,3 +2,4 @@
# will have compiled files and executables
/target/
/gen/schemas
+google-services.json
diff --git a/rust/cloud-storage/.gitignore b/rust/cloud-storage/.gitignore
index a8bac09d6f..2517c3140d 100644
--- a/rust/cloud-storage/.gitignore
+++ b/rust/cloud-storage/.gitignore
@@ -13,3 +13,4 @@
# Jetbrains IDE files
**/.idea/
+**/.helix/
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 7118fa2f17..94bda9a26c 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -481,7 +481,6 @@ dependencies = [
"http-body-util",
"jsonwebtoken",
"macro_auth",
- "macro_autoupdate_router",
"macro_cache_client",
"macro_cors",
"macro_db_client",
@@ -497,6 +496,7 @@ dependencies = [
"model",
"model_notifications",
"models_team",
+ "native_app_service",
"non_empty",
"notification_service_client",
"openssl",
@@ -4728,23 +4728,6 @@ dependencies = [
"urlencoding",
]
-[[package]]
-name = "macro_autoupdate_router"
-version = "0.1.0"
-dependencies = [
- "axum",
- "cool_asserts",
- "macro_env",
- "reqwest",
- "semver",
- "serde",
- "strum",
- "thiserror 2.0.17",
- "tokio",
- "tracing",
- "url",
-]
-
[[package]]
name = "macro_axum_utils"
version = "0.1.0"
@@ -5601,6 +5584,25 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "native_app_service"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "cool_asserts",
+ "macro_env",
+ "reqwest",
+ "semver",
+ "serde",
+ "serde_json",
+ "strum",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "url",
+]
+
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 09a1428e53..ac714aab77 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -45,7 +45,6 @@ futures = { workspace = true }
http-body-util = { workspace = true }
jsonwebtoken = { workspace = true }
macro_auth = { path = "../macro_auth" }
-macro_autoupdate_router = { path = "../macro_autoupdate_router" }
macro_cache_client = { path = "../macro_cache_client", default-features = false, features = [
"auth",
"auth_rate_limit",
@@ -73,6 +72,7 @@ mockall = { workspace = true }
model = { path = "../model" }
model_notifications = { path = "../model_notifications" }
models_team = { path = "../models_team" }
+native_app_service = { path = "../native_app_service" }
non_empty = { path = "../non_empty" }
notification_service_client = { path = "../notification_service_client" }
openssl = { workspace = true }
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index c6b651ba0e..e8528cff3a 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -6,6 +6,7 @@ use macro_cache_client::MacroCache;
use macro_env::Environment;
use macro_env_var::env_var;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};
use remote_env_var::LocalOrRemoteSecret;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
@@ -43,6 +44,7 @@ pub(crate) struct ApiContext {
UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
>,
>,
+ pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
}
env_var! {
diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rs
index 06607a9a92..0f7956f9aa 100644
--- a/rust/cloud-storage/authentication_service/src/api/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs
@@ -6,6 +6,7 @@ use axum::http::HeaderName;
use axum::http::Method;
use axum::middleware::Next;
use macro_auth::constant::MACRO_REFRESH_TOKEN_HEADER;
+use native_app_service::inbound::RouterState;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
@@ -69,6 +70,11 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<(
fn api_router(state: ApiContext) -> Router<ApiContext> {
Router::new()
+ .merge(native_app_service::inbound::native_app_router(
+ RouterState {
+ inner: state.native_app_service.clone(),
+ },
+ ))
.nest("/internal", internal::router())
.nest("/permissions", permissions::router(state.jwt_args.clone()))
.nest("/login", login::router(state.clone()))
@@ -76,48 +82,12 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
.nest("/oauth", oauth::router(state.clone()))
.nest("/oauth2", oauth2::router())
.nest("/user", user::router(state.clone(), state.jwt_args.clone()))
- .nest(
- "/update",
- macro_autoupdate_router::routes(state.environment),
- )
.nest(
"/team",
team::router(state.jwt_args.clone()).layer(ServiceBuilder::new().layer(
axum::middleware::from_fn(macro_middleware::tracking::attach_ip_context_handler),
)),
)
- // .nest(
- // "/merge",
- // merge::router().layer(
- // ServiceBuilder::new()
- // .layer(axum::middleware::from_fn(
- // macro_middleware::tracking::attach_ip_context_handler,
- // ))
- // .layer(axum::middleware::from_fn_with_state(
- // state.jwt_args.clone(),
- // macro_middleware::auth::decode_jwt::handler,
- // )),
- // ),
- // )
- // .nest(
- // "/email",
- // email::router(state.jwt_args.clone()).layer(ServiceBuilder::new().layer(
- // axum::middleware::from_fn(macro_middleware::tracking::attach_ip_context_handler),
- // )),
- // )
- // .nest(
- // "/link",
- // link::router().layer(
- // ServiceBuilder::new()
- // .layer(axum::middleware::from_fn(
- // macro_middleware::tracking::attach_ip_context_handler,
- // ))
- // .layer(axum::middleware::from_fn_with_state(
- // state.jwt_args.clone(),
- // macro_middleware::auth::decode_jwt::handler,
- // )),
- // ),
- // )
.nest("/jwt", jwt::router(state.jwt_args))
.nest("/session", session::router())
.nest(
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 1db94a59cb..33d8e771be 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -5,6 +5,10 @@ use document_storage_service_client::DocumentStorageServiceClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use native_app_service::{
+ domain::{models::PlatformData, service::NativeAppServiceImpl},
+ outbound::DefaultBundleFetcher,
+};
use notification_service_client::NotificationServiceClient;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
@@ -227,9 +231,22 @@ async fn main() -> anyhow::Result<()> {
stripe_webhook_secret,
user_roles_and_permissions_service: Arc::new(user_roles_and_permissions_service),
teams_service: Arc::new(teams_service_impl),
+ native_app_service: Arc::new(NativeAppServiceImpl {
+ bundle_fetcher: DefaultBundleFetcher::default(),
+ environment: config.environment,
+ platform_data: PlatformData {
+ ios_development_team_id: IOS_DEVELOPMENT_TEAM_ID.to_string(),
+ ios_app_bundle_id: IOS_APP_BUNDLE_ID.to_string(),
+ },
+ }),
},
config.port,
)
.await?;
Ok(())
}
+
+// SAFETY: this is not a secret value
+const IOS_DEVELOPMENT_TEAM_ID: &str = "TY74Q77JBD";
+// SAFETY: this is not a secret value
+const IOS_APP_BUNDLE_ID: &str = "com.macro.app.prod";
diff --git a/rust/cloud-storage/macro_autoupdate_router/src/lib.rs b/rust/cloud-storage/macro_autoupdate_router/src/lib.rs
deleted file mode 100644
index 3dcc16a7ae..0000000000
--- a/rust/cloud-storage/macro_autoupdate_router/src/lib.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-#![deny(missing_docs)]
-//! This crate provides the serverside handlers required to dynamically update the tauri application
-//! Consumers of this crate should integrate the router
-//! by calling [axum::Router::with_state]
-
-use axum::{
- Json, Router,
- extract::{Path, State},
- response::IntoResponse,
- routing::get,
-};
-use macro_env::{Environment, ext::frontend_url::FrontendUrl};
-use serde::{Deserialize, Serialize};
-use std::str::FromStr;
-use thiserror::Error;
-use url::Url;
-
-#[cfg(test)]
-mod tests;
-
-/// the external facing router to be merged with the root router
-pub fn routes<S>(env: Environment) -> Router<S> {
- Router::new()
- .route(
- "/desktop/:desktop_target/:arch/:current_version",
- get(desktop_update_handler),
- )
- .route(
- "/bundle/:all_target/:arch/:current_version",
- get(bundle_update_handler),
- )
- .with_state(env)
-}
-
-/// The possible input desktop operating systems
-/// See https://v2.tauri.app/plugin/updater/#dynamic-update-server
-#[derive(Debug, Deserialize, Clone, Copy)]
-#[serde(rename_all = "lowercase")]
-#[cfg_attr(test, derive(strum::EnumIter))]
-pub enum DesktopTarget {
- /// the requesting client is on linux
- Linux,
- /// the requesting client is on Windows
- Windows,
- /// the requesting client is on Darwin/MacOS
- Darwin,
-}
-
-/// The possible input mobile operating systems
-#[derive(Debug, Deserialize, Clone, Copy)]
-#[serde(rename_all = "lowercase")]
-#[cfg_attr(test, derive(strum::EnumIter))]
-pub enum MobileTarget {
- /// the requesting client is on ios
- Ios,
- /// the requesting client is on android
- Android,
-}
-
-/// an enumeration of all possible tauri targets
-#[derive(Debug, Deserialize, Clone, Copy)]
-#[serde(untagged)]
-pub enum AllTargets {
- /// desktop operating system
- Desktop(DesktopTarget),
- /// mobile operating system
- Mobile(MobileTarget),
-}
-
-/// The possible input architechtures
-/// See https://v2.tauri.app/plugin/updater/#dynamic-update-server
-#[derive(Debug, Deserialize, Clone, Copy)]
-#[cfg_attr(test, derive(strum::EnumIter))]
-#[serde(rename_all = "lowercase")]
-pub enum Arch {
- /// the x86 architecture
- X86_64,
- /// this is an old and mostly deprecated system architecture
- /// but it technically could be sent
- I686,
- /// most phones and apple devices use this arch
- Aarch64,
- /// predecessor to the more modern arm architecture
- Armv7,
-}
-
-/// a struct which indicates the client should upgrade their desktop app
-/// This means the system level rust binary will be updated
-#[derive(Debug, Serialize)]
-struct DesktopUpdate {
- /// code signing signature of the update bundle
- /// see https://v2.tauri.app/plugin/updater
- signature: Vec<u8>,
- /// the remaining properties of the update
- #[serde(flatten)]
- inner: BundleUpdate,
-}
-
-impl IntoResponse for DesktopUpdate {
- fn into_response(self) -> axum::response::Response {
- Json(self).into_response()
- }
-}
-
-/// a struct which indicates how to update only the javascript bundle of the application
-#[derive(Debug, Serialize)]
-pub struct BundleUpdate {
- /// the version that we are going to update to
- version: semver::Version,
- /// some optional notes about the update
- notes: Option<String>,
- /// the fully qualified Url where the update bundle exists
- url: Url,
-}
-
-impl IntoResponse for BundleUpdate {
- fn into_response(self) -> axum::response::Response {
- Json(self).into_response()
- }
-}
-
-#[derive(Debug)]
-enum UpdateResult<T> {
- UpdateFound(T),
- NoUpdateAvailable,
-}
-
-impl<T> IntoResponse for UpdateResult<T>
-where
- T: IntoResponse,
-{
- fn into_response(self) -> axum::response::Response {
- match self {
- UpdateResult::UpdateFound(update_found) => update_found.into_response(),
- UpdateResult::NoUpdateAvailable => (reqwest::StatusCode::NO_CONTENT).into_response(),
- }
- }
-}
-
-#[axum::debug_handler(state = Environment)]
-#[tracing::instrument(ret)]
-async fn desktop_update_handler(
- Path((target, arch, cur_ver)): Path<(DesktopTarget, Arch, semver::Version)>,
-) -> UpdateResult<DesktopUpdate> {
- UpdateResult::NoUpdateAvailable
-}
-
-#[axum::debug_handler(state = Environment)]
-#[tracing::instrument(ret)]
-async fn bundle_update_handler(
- Path(params): Path<(AllTargets, Arch, semver::Version)>,
- State(env): State<Environment>,
-) -> UpdateResult<BundleUpdate> {
- match bundle_update_handle_inner::<DefaultBundleFetcher>(params, env).await {
- Ok(Some(update)) => UpdateResult::UpdateFound(update),
- Ok(None) | Err(_) => UpdateResult::NoUpdateAvailable,
- }
-}
-
-#[derive(Debug, Error)]
-enum UpdateErr {
- #[error("A network error occurred: {0:?}")]
- Reqwest(#[from] reqwest::Error),
- #[error("Failed to parse semver {0}")]
- Semver(#[from] semver::Error),
-}
-
-/// the inner implementation of [bundle_update_handler]
-/// this allows dependency injection of [GetAppSemver] for testing purposes
-/// returns an `Option<BundleUpdate>` to denote that no errors occurred but there is no
-/// update available
-#[tracing::instrument(err)]
-async fn bundle_update_handle_inner<T: GetJsBundleSemver>(
- (target, arch, cur_ver): (AllTargets, Arch, semver::Version),
- env: Environment,
-) -> Result<Option<BundleUpdate>, UpdateErr> {
- let most_recent = T::get_app_semver(&env).await?;
- if most_recent > cur_ver {
- return Ok(Some(BundleUpdate {
- version: most_recent,
- notes: None,
- url: T::get_app_bundle_path(&env),
- }));
- }
-
- Ok(None)
-}
-
-trait GetJsBundleSemver {
- /// fetch the semver of the current app over the network
- fn get_app_semver(
- env: &Environment,
- ) -> impl Future<Output = Result<semver::Version, UpdateErr>>;
- /// get the Url of the bundle
- fn get_app_bundle_path(env: &Environment) -> Url;
-}
-
-/// unit struct to define the default behaviour of the service
-/// (not mocked service)
-struct DefaultBundleFetcher;
-
-/// the name of the semver file as it exists in the s3 bucket
-static SEMVER_FILE_NAME: &str = "/app/semver.txt";
-static BUNDLE_ARCHIVE_NAME: &str = "app-archive.zip";
-
-impl GetJsBundleSemver for DefaultBundleFetcher {
- #[tracing::instrument(ret, err)]
- async fn get_app_semver(env: &Environment) -> Result<semver::Version, UpdateErr> {
- let url = env.get_frontend_url().join(SEMVER_FILE_NAME).unwrap();
- let res = reqwest::get(url).await?.error_for_status()?.text().await?;
- let cur_ver = semver::Version::from_str(res.trim())?;
- Ok(cur_ver)
- }
-
- fn get_app_bundle_path(env: &Environment) -> Url {
- env.get_frontend_url().join(BUNDLE_ARCHIVE_NAME).unwrap()
- }
-}
diff --git a/rust/cloud-storage/macro_autoupdate_router/src/tests.rs b/rust/cloud-storage/macro_autoupdate_router/src/tests.rs
deleted file mode 100644
index 9125c0e760..0000000000
--- a/rust/cloud-storage/macro_autoupdate_router/src/tests.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-use super::*;
-use cool_asserts::assert_matches;
-use semver::Version;
-use strum::IntoEnumIterator;
-
-#[test]
-fn all_urls_work() {
- let _urls = Environment::iter()
- .map(|e| DefaultBundleFetcher::get_app_bundle_path(&e))
- .collect::<Vec<_>>();
-}
-
-struct MockBundleFetcher;
-
-impl GetJsBundleSemver for MockBundleFetcher {
- async fn get_app_semver(_env: &Environment) -> Result<semver::Version, UpdateErr> {
- Ok("1.1.1".parse().unwrap())
- }
-
- fn get_app_bundle_path(_env: &Environment) -> Url {
- "https://example.com".parse().unwrap()
- }
-}
-
-#[tokio::test]
-async fn it_should_not_downgrade_mobile() {
- let semver: Version = "1.2.1".parse().unwrap();
- let iter = MobileTarget::iter()
- .flat_map(move |target| {
- let semver = semver.clone();
- Arch::iter().map(move |arch| (AllTargets::Mobile(target), arch, semver.clone()))
- })
- .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
- .map(|(p, e)| bundle_update_handle_inner::<MockBundleFetcher>(p, e));
-
- for fut in iter {
- assert_matches!(fut.await, Ok(None))
- }
-}
-
-#[tokio::test]
-async fn it_should_upgrade_mobile() {
- let semver: Version = "1.0.1".parse().unwrap();
- let iter = MobileTarget::iter()
- .flat_map(move |target| {
- let semver = semver.clone();
- Arch::iter().map(move |arch| (AllTargets::Mobile(target), arch, semver.clone()))
- })
- .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
- .map(|(p, e)| bundle_update_handle_inner::<MockBundleFetcher>(p, e));
-
- for fut in iter {
- assert_matches!(fut.await, Ok(Some(BundleUpdate { version, notes: _, url })) => {
- assert_eq!(version.to_string(), "1.1.1");
- assert_eq!(url.as_str(), "https://example.com/");
- })
- }
-}
-
-#[tokio::test]
-async fn it_should_not_downgrade_desktop() {
- let semver: Version = "1.2.1".parse().unwrap();
- let iter = DesktopTarget::iter()
- .flat_map(move |target| {
- let semver = semver.clone();
- Arch::iter().map(move |arch| (AllTargets::Desktop(target), arch, semver.clone()))
- })
- .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
- .map(|(p, e)| bundle_update_handle_inner::<MockBundleFetcher>(p, e));
-
- for fut in iter {
- assert_matches!(fut.await, Ok(None));
- }
-}
-
-#[tokio::test]
-async fn it_should_upgrade_desktop() {
- let semver: Version = "1.0.1".parse().unwrap();
- let iter = DesktopTarget::iter()
- .flat_map(move |target| {
- let semver = semver.clone();
- Arch::iter().map(move |arch| (AllTargets::Desktop(target), arch, semver.clone()))
- })
- .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
- .map(|(p, e)| bundle_update_handle_inner::<MockBundleFetcher>(p, e));
-
- for fut in iter {
- assert_matches!(fut.await, Ok(Some(BundleUpdate { version, notes: _, url })) => {
- assert_eq!(version.to_string(), "1.1.1");
- assert_eq!(url.as_str(), "https://example.com/");
- })
- }
-}
diff --git a/rust/cloud-storage/macro_autoupdate_router/Cargo.toml b/rust/cloud-storage/native_app_service/Cargo.toml
similarity index 87%
rename from rust/cloud-storage/macro_autoupdate_router/Cargo.toml
rename to rust/cloud-storage/native_app_service/Cargo.toml
index 2c02250d86..8a1a87e2eb 100644
--- a/rust/cloud-storage/macro_autoupdate_router/Cargo.toml
+++ b/rust/cloud-storage/native_app_service/Cargo.toml
@@ -1,15 +1,17 @@
[package]
edition = "2024"
-name = "macro_autoupdate_router"
+name = "native_app_service"
publish = false
version = "0.1.0"
[dependencies]
+anyhow = { workspace = true }
axum = { workspace = true, features = ["macros"] }
macro_env = { path = "../macro_env", features = ["frontend_url"] }
reqwest = { workspace = true }
semver = { version = "1", features = ["serde"] }
serde = { workspace = true, features = ["derive"] }
+serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
url = { workspace = true, features = ["serde"] }
diff --git a/rust/cloud-storage/native_app_service/src/domain.rs b/rust/cloud-storage/native_app_service/src/domain.rs
new file mode 100644
index 0000000000..0459345a49
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/domain.rs
@@ -0,0 +1,6 @@
+/// the model structs and fn impls
+pub mod models;
+/// ports for communication with the outside world
+pub mod ports;
+/// implementation of the service via composing ports
+pub mod service;
diff --git a/rust/cloud-storage/native_app_service/src/domain/models.rs b/rust/cloud-storage/native_app_service/src/domain/models.rs
new file mode 100644
index 0000000000..268d4fcb0a
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/domain/models.rs
@@ -0,0 +1,148 @@
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use thiserror::Error;
+use url::Url;
+
+/// The possible input desktop operating systems
+/// See https://v2.tauri.app/plugin/updater/#dynamic-update-server
+#[derive(Debug, Deserialize, Clone, Copy)]
+#[serde(rename_all = "lowercase")]
+#[cfg_attr(test, derive(strum::EnumIter))]
+pub enum DesktopTarget {
+ /// the requesting client is on linux
+ Linux,
+ /// the requesting client is on Windows
+ Windows,
+ /// the requesting client is on Darwin/MacOS
+ Darwin,
+}
+
+/// The possible input mobile operating systems
+#[derive(Debug, Deserialize, Clone, Copy)]
+#[serde(rename_all = "lowercase")]
+#[cfg_attr(test, derive(strum::EnumIter))]
+pub enum MobileTarget {
+ /// the requesting client is on android
+ Android,
+ /// the requesting client is on ios
+ Ios,
+}
+
+/// an enumeration of all possible tauri targets
+#[derive(Debug, Deserialize, Clone, Copy)]
+#[serde(untagged)]
+pub enum AllTargets {
+ /// desktop operating system
+ Desktop(DesktopTarget),
+ /// mobile operating system
+ Mobile(MobileTarget),
+}
+
+/// The possible input architechtures
+/// See https://v2.tauri.app/plugin/updater/#dynamic-update-server
+#[derive(Debug, Deserialize, Clone, Copy)]
+#[cfg_attr(test, derive(strum::EnumIter))]
+#[serde(rename_all = "lowercase")]
+pub enum Arch {
+ /// the x86 architecture
+ X86_64,
+ /// this is an old and mostly deprecated system architecture
+ /// but it technically could be sent
+ I686,
+ /// most phones and apple devices use this arch
+ Aarch64,
+ /// predecessor to the more modern arm architecture
+ Armv7,
+}
+
+/// a struct which indicates the client should upgrade their desktop app
+/// This means the system level rust binary will be updated
+#[derive(Debug, Serialize)]
+pub struct DesktopUpdate {
+ /// code signing signature of the update bundle
+ /// see https://v2.tauri.app/plugin/updater
+ signature: Vec<u8>,
+ /// the remaining properties of the update
+ #[serde(flatten)]
+ inner: BundleUpdate,
+}
+
+/// a struct which indicates how to update only the javascript bundle of the application
+#[derive(Debug, Serialize)]
+pub struct BundleUpdate {
+ /// the version that we are going to update to
+ pub(crate) version: semver::Version,
+ /// some optional notes about the update
+ pub(crate) notes: Option<String>,
+ /// the fully qualified Url where the update bundle exists
+ pub(crate) url: Url,
+}
+
+/// The payload to check if there is a native app js bundle update available
+#[derive(Debug)]
+pub struct BundleUpdateRequest {
+ /// the target which is requesting the update
+ pub target: AllTargets,
+ /// the arch of the target
+ pub arch: Arch,
+ /// the current verison of the bundle
+ pub semver: semver::Version,
+}
+
+/// the name of the semver file as it exists in the s3 bucket
+pub static SEMVER_FILE_NAME: &str = "/app/semver.txt";
+/// the name of the bundle file as it exists in the s3 bucket
+pub static BUNDLE_ARCHIVE_NAME: &str = "app-archive.zip";
+
+/// the typed of errors that can occur while querying the bundle state
+#[derive(Debug, Error)]
+pub enum UpdateErr {
+ /// a network error has occirred
+ #[error("A network error occurred: {0:?}")]
+ Network(#[from] anyhow::Error),
+ /// failed to parse a semver string
+ #[error("Failed to parse semver {0}")]
+ Semver(#[from] semver::Error),
+}
+
+/// contains information about bundle ids for various app platforms
+pub struct PlatformData {
+ /// the ios xcode dev team id
+ pub ios_development_team_id: String,
+ /// the ios xcode bundle id
+ pub ios_app_bundle_id: String,
+}
+
+/// trait which defines how we fetch platform verification data for different platforms
+pub trait PlatformVerifier {
+ /// the type of the output data
+ type VerifierPayload: Serialize;
+
+ /// get the verifier payload
+ fn get_payload(&self, platform_data: &PlatformData) -> Self::VerifierPayload;
+}
+
+/// the concrete struct which is used to produce the iOS verification payload
+pub struct IOSVerifier;
+
+impl PlatformVerifier for IOSVerifier {
+ type VerifierPayload = serde_json::Value;
+
+ fn get_payload(&self, platform_data: &PlatformData) -> Self::VerifierPayload {
+ json!({
+ "applinks": {
+ "details": [
+ {
+ "appIDs": [format_args!("{}.{}", platform_data.ios_development_team_id, platform_data.ios_app_bundle_id)],
+ "components": [
+ {
+ "/": "/app/*",
+ "comment": "Matches any URL whose path starts with /app/"
+ }
+ ]
+ }
+ ]
+ }
+ })
+ }
+}
diff --git a/rust/cloud-storage/native_app_service/src/domain/ports.rs b/rust/cloud-storage/native_app_service/src/domain/ports.rs
new file mode 100644
index 0000000000..93b2a4f348
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/domain/ports.rs
@@ -0,0 +1,27 @@
+use crate::domain::models::{BundleUpdate, BundleUpdateRequest, PlatformVerifier, UpdateErr};
+use macro_env::Environment;
+use url::Url;
+
+/// outbound trait for sending network requests to query the bundle state
+pub trait GetJsBundleSemver: Send + Sync + 'static {
+ /// fetch the semver of the current app over the network
+ fn get_app_semver(
+ &self,
+ env: &Environment,
+ ) -> impl Future<Output = Result<semver::Version, UpdateErr>> + Send;
+ /// get the Url of the bundle
+ fn get_app_bundle_path(&self, env: &Environment) -> Url;
+}
+
+/// the service level trait for dealing with tauri app integration
+pub trait NativeAppService: Send + Sync + 'static {
+ /// returns an `Option<BundleUpdate>` to denote that no errors occurred but there is no
+ /// update available
+ fn get_bundle_update(
+ &self,
+ req: BundleUpdateRequest,
+ ) -> impl Future<Output = Result<Option<BundleUpdate>, UpdateErr>> + Send;
+
+ /// retrieve the verification payload for some platform T
+ fn verification_data<T: PlatformVerifier>(&self, req: T) -> T::VerifierPayload;
+}
diff --git a/rust/cloud-storage/native_app_service/src/domain/service.rs b/rust/cloud-storage/native_app_service/src/domain/service.rs
new file mode 100644
index 0000000000..540de2a5d4
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/domain/service.rs
@@ -0,0 +1,52 @@
+use macro_env::Environment;
+
+use crate::domain::{
+ models::{BundleUpdate, BundleUpdateRequest, PlatformData, PlatformVerifier, UpdateErr},
+ ports::{GetJsBundleSemver, NativeAppService},
+};
+
+/// the concrete struct which implements [NativeAppService]
+pub struct NativeAppServiceImpl<T> {
+ /// the implementation of [GetJsBundleSemver]
+ pub bundle_fetcher: T,
+ /// the environment we are running in
+ pub environment: Environment,
+
+ /// the platform data for various platforms
+ pub platform_data: PlatformData,
+}
+
+impl<T> NativeAppService for NativeAppServiceImpl<T>
+where
+ T: GetJsBundleSemver,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn get_bundle_update(
+ &self,
+ req: BundleUpdateRequest,
+ ) -> Result<Option<BundleUpdate>, UpdateErr> {
+ let BundleUpdateRequest {
+ target: _,
+ arch: _,
+ semver: cur_ver,
+ } = req;
+
+ let most_recent = self
+ .bundle_fetcher
+ .get_app_semver(&self.environment)
+ .await?;
+ if most_recent > cur_ver {
+ return Ok(Some(BundleUpdate {
+ version: most_recent,
+ notes: None,
+ url: self.bundle_fetcher.get_app_bundle_path(&self.environment),
+ }));
+ }
+
+ Ok(None)
+ }
+
+ fn verification_data<P: PlatformVerifier>(&self, req: P) -> P::VerifierPayload {
+ req.get_payload(&self.platform_data)
+ }
+}
diff --git a/rust/cloud-storage/native_app_service/src/inbound.rs b/rust/cloud-storage/native_app_service/src/inbound.rs
new file mode 100644
index 0000000000..dcdea2d428
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/inbound.rs
@@ -0,0 +1,95 @@
+use std::sync::Arc;
+
+use axum::Json;
+use axum::response::IntoResponse;
+use axum::{
+ Router,
+ extract::{Path, State},
+ routing::get,
+};
+
+use crate::domain::models::{
+ AllTargets, Arch, BundleUpdate, BundleUpdateRequest, DesktopTarget, DesktopUpdate, IOSVerifier,
+};
+use crate::domain::ports::NativeAppService;
+
+/// the type of router state for this axum router
+pub struct RouterState<S> {
+ /// the inner service implementation S
+ pub inner: Arc<S>,
+}
+
+impl<S> Clone for RouterState<S> {
+ fn clone(&self) -> Self {
+ Self {
+ inner: self.inner.clone(),
+ }
+ }
+}
+
+/// the external facing router to be merged with the root router
+pub fn native_app_router<S: NativeAppService, T>(state: RouterState<S>) -> Router<T> {
+ Router::new()
+ .route(
+ "/update/desktop/:desktop_target/:arch/:current_version",
+ get(desktop_update_handler),
+ )
+ .route(
+ "/update/bundle/:all_target/:arch/:current_version",
+ get(bundle_update_handler),
+ )
+ .route(
+ "/.well-known/apple-app-site-association",
+ get(verify_ios_app_handler),
+ )
+ .with_state(state)
+}
+
+#[tracing::instrument(ret)]
+async fn desktop_update_handler(
+ Path((target, arch, cur_ver)): Path<(DesktopTarget, Arch, semver::Version)>,
+) -> UpdateResult<Json<DesktopUpdate>> {
+ UpdateResult::NoUpdateAvailable
+}
+
+async fn bundle_update_handler<S: NativeAppService>(
+ State(s): State<RouterState<S>>,
+ Path((target, arch, semver)): Path<(AllTargets, Arch, semver::Version)>,
+) -> UpdateResult<Json<BundleUpdate>> {
+ match s
+ .inner
+ .get_bundle_update(BundleUpdateRequest {
+ target,
+ arch,
+ semver,
+ })
+ .await
+ {
+ Ok(Some(update)) => UpdateResult::UpdateFound(Json(update)),
+ Ok(None) | Err(_) => UpdateResult::NoUpdateAvailable,
+ }
+}
+
+#[derive(Debug)]
+enum UpdateResult<T> {
+ UpdateFound(T),
+ NoUpdateAvailable,
+}
+
+impl<T> IntoResponse for UpdateResult<T>
+where
+ T: IntoResponse,
+{
+ fn into_response(self) -> axum::response::Response {
+ match self {
+ UpdateResult::UpdateFound(update_found) => update_found.into_response(),
+ UpdateResult::NoUpdateAvailable => (reqwest::StatusCode::NO_CONTENT).into_response(),
+ }
+ }
+}
+
+async fn verify_ios_app_handler<S: NativeAppService>(
+ State(s): State<RouterState<S>>,
+) -> Json<serde_json::Value> {
+ Json(s.inner.verification_data(IOSVerifier))
+}
diff --git a/rust/cloud-storage/native_app_service/src/lib.rs b/rust/cloud-storage/native_app_service/src/lib.rs
new file mode 100644
index 0000000000..60506146a6
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/lib.rs
@@ -0,0 +1,14 @@
+#![deny(missing_docs)]
+//! This crate provides the serverside handlers required to dynamically update the tauri application
+//! Consumers of this crate should integrate the router
+//! by calling [axum::Router::with_state]
+
+/// contains domain level business logic
+pub mod domain;
+/// the outbound implementations of ports
+pub mod inbound;
+/// adapter for incoming data into the service
+pub mod outbound;
+
+#[cfg(test)]
+mod tests;
diff --git a/rust/cloud-storage/native_app_service/src/outbound.rs b/rust/cloud-storage/native_app_service/src/outbound.rs
new file mode 100644
index 0000000000..b974ff0e72
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/outbound.rs
@@ -0,0 +1,48 @@
+use crate::domain::{
+ models::{BUNDLE_ARCHIVE_NAME, SEMVER_FILE_NAME, UpdateErr},
+ ports::GetJsBundleSemver,
+};
+use macro_env::{Environment, ext::frontend_url::FrontendUrl};
+use std::str::FromStr;
+use url::Url;
+
+/// unit struct to define the default behaviour of the service
+/// (not mocked service)
+pub struct DefaultBundleFetcher {
+ /// the file name of the semver file in the js app s3 bucket
+ pub semver_file_name: &'static str,
+ /// the name of the bundle archive on the s3 bucket
+ pub bundle_archive_name: &'static str,
+}
+
+impl Default for DefaultBundleFetcher {
+ fn default() -> Self {
+ Self {
+ semver_file_name: SEMVER_FILE_NAME,
+ bundle_archive_name: BUNDLE_ARCHIVE_NAME,
+ }
+ }
+}
+
+impl GetJsBundleSemver for DefaultBundleFetcher {
+ #[tracing::instrument(skip(self), ret, err)]
+ async fn get_app_semver(&self, env: &Environment) -> Result<semver::Version, UpdateErr> {
+ let url = env.get_frontend_url().join(self.semver_file_name).unwrap();
+ let res = reqwest::get(url)
+ .await
+ .map_err(anyhow::Error::from)?
+ .error_for_status()
+ .map_err(anyhow::Error::from)?
+ .text()
+ .await
+ .map_err(anyhow::Error::from)?;
+ let cur_ver = semver::Version::from_str(res.trim())?;
+ Ok(cur_ver)
+ }
+
+ fn get_app_bundle_path(&self, env: &Environment) -> Url {
+ env.get_frontend_url()
+ .join(self.bundle_archive_name)
+ .unwrap()
+ }
+}
diff --git a/rust/cloud-storage/native_app_service/src/tests.rs b/rust/cloud-storage/native_app_service/src/tests.rs
new file mode 100644
index 0000000000..f2abe313cd
--- /dev/null
+++ b/rust/cloud-storage/native_app_service/src/tests.rs
@@ -0,0 +1,174 @@
+use crate::{
+ domain::{
+ self,
+ models::{
+ AllTargets, Arch, BundleUpdate, DesktopTarget, MobileTarget, PlatformData, UpdateErr,
+ },
+ ports::{GetJsBundleSemver, NativeAppService},
+ service::NativeAppServiceImpl,
+ },
+ outbound::DefaultBundleFetcher,
+};
+use macro_env::Environment;
+use reqwest::Url;
+
+use cool_asserts::assert_matches;
+use semver::Version;
+use strum::IntoEnumIterator;
+
+#[test]
+fn all_urls_work() {
+ let fetcher = DefaultBundleFetcher {
+ semver_file_name: "",
+ bundle_archive_name: "",
+ };
+ let _urls = Environment::iter()
+ .map(|e| fetcher.get_app_bundle_path(&e))
+ .collect::<Vec<_>>();
+}
+
+struct MockBundleFetcher;
+
+impl GetJsBundleSemver for MockBundleFetcher {
+ async fn get_app_semver(&self, _env: &Environment) -> Result<semver::Version, UpdateErr> {
+ Ok("1.1.1".parse().unwrap())
+ }
+
+ fn get_app_bundle_path(&self, _env: &Environment) -> Url {
+ "https://example.com".parse().unwrap()
+ }
+}
+
+fn mock_platform_data() -> PlatformData {
+ PlatformData {
+ ios_development_team_id: String::new(),
+ ios_app_bundle_id: String::new(),
+ }
+}
+
+#[tokio::test]
+async fn it_should_not_downgrade_mobile() {
+ let semver: Version = "1.2.1".parse().unwrap();
+
+ let iter = MobileTarget::iter()
+ .flat_map(move |target| {
+ let semver = semver.clone();
+ Arch::iter().map(move |arch| (AllTargets::Mobile(target), arch, semver.clone()))
+ })
+ .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
+ .map(|((target, arch, semver), e)| async move {
+ let service = NativeAppServiceImpl {
+ bundle_fetcher: MockBundleFetcher,
+ environment: e,
+ platform_data: mock_platform_data(),
+ };
+
+ service
+ .get_bundle_update(domain::models::BundleUpdateRequest {
+ target,
+ arch,
+ semver,
+ })
+ .await
+ });
+
+ for fut in iter {
+ assert_matches!(fut.await, Ok(None))
+ }
+}
+
+#[tokio::test]
+async fn it_should_upgrade_mobile() {
+ let semver: Version = "1.0.1".parse().unwrap();
+ let iter = MobileTarget::iter()
+ .flat_map(move |target| {
+ let semver = semver.clone();
+ Arch::iter().map(move |arch| (AllTargets::Mobile(target), arch, semver.clone()))
+ })
+ .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
+ .map(|((target, arch, semver), e)| async move {
+ let service = NativeAppServiceImpl {
+ bundle_fetcher: MockBundleFetcher,
+ environment: e,
+ platform_data: mock_platform_data(),
+ };
+
+ service
+ .get_bundle_update(domain::models::BundleUpdateRequest {
+ target,
+ arch,
+ semver,
+ })
+ .await
+ });
+
+ for fut in iter {
+ assert_matches!(fut.await, Ok(Some(BundleUpdate { version, notes: _, url })) => {
+ assert_eq!(version.to_string(), "1.1.1");
+ assert_eq!(url.as_str(), "https://example.com/");
+ })
+ }
+}
+
+#[tokio::test]
+async fn it_should_not_downgrade_desktop() {
+ let semver: Version = "1.2.1".parse().unwrap();
+ let iter = DesktopTarget::iter()
+ .flat_map(move |target| {
+ let semver = semver.clone();
+ Arch::iter().map(move |arch| (AllTargets::Desktop(target), arch, semver.clone()))
+ })
+ .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
+ .map(|((target, arch, semver), e)| async move {
+ let service = NativeAppServiceImpl {
+ bundle_fetcher: MockBundleFetcher,
+ environment: e,
+ platform_data: mock_platform_data(),
+ };
+
+ service
+ .get_bundle_update(domain::models::BundleUpdateRequest {
+ target,
+ arch,
+ semver,
+ })
+ .await
+ });
+
+ for fut in iter {
+ assert_matches!(fut.await, Ok(None));
+ }
+}
+
+#[tokio::test]
+async fn it_should_upgrade_desktop() {
+ let semver: Version = "1.0.1".parse().unwrap();
+ let iter = DesktopTarget::iter()
+ .flat_map(move |target| {
+ let semver = semver.clone();
+ Arch::iter().map(move |arch| (AllTargets::Desktop(target), arch, semver.clone()))
+ })
+ .flat_map(|p| Environment::iter().map(move |e| (p.clone(), e)))
+ .map(|((target, arch, semver), e)| async move {
+ let service = NativeAppServiceImpl {
+ bundle_fetcher: MockBundleFetcher,
+ environment: e,
+ platform_data: mock_platform_data(),
+ };
+
+ service
+ .get_bundle_update(domain::models::BundleUpdateRequest {
+ target,
+ arch,
+ semver,
+ })
+ .await
+ });
+
+ for fut in iter {
+ assert_matches!(fut.await, Ok(Some(BundleUpdate { version, notes: _, url })) => {
+ assert_eq!(version.to_string(), "1.1.1");
+ assert_eq!(url.as_str(), "https://example.com/");
+ })
+ }
+}