Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
chore: refactor updater (#7377)
hiento0940b847c51e11
diff --git a/.github/workflows/template-tauri-build-linux-x64-external.yml b/.github/workflows/template-tauri-build-linux-x64-external.ymlindex e40177f9d..501bb497c 100644--- a/.github/workflows/template-tauri-build-linux-x64-external.yml+++ b/.github/workflows/template-tauri-build-linux-x64-external.yml@@ -107,7 +107,11 @@ jobs:ctoml ./src-tauri/Cargo.toml dependencies.tauri.features[] "devtools"if [ "${{ inputs.channel }}" != "stable" ]; then- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.jsonchmod +x .github/scripts/rename-tauri-app.sh.github/scripts/rename-tauri-app.sh ./src-tauri/tauri.conf.json ${{ inputs.channel }}diff --git a/.github/workflows/template-tauri-build-linux-x64-flatpak.yml b/.github/workflows/template-tauri-build-linux-x64-flatpak.ymlindex 262434c2a..7fc2cf9af 100644--- a/.github/workflows/template-tauri-build-linux-x64-flatpak.yml+++ b/.github/workflows/template-tauri-build-linux-x64-flatpak.yml@@ -40,6 +40,8 @@ on:required: falseTAURI_SIGNING_PRIVATE_KEY_PASSWORD:required: false+ JAN_SIGNING_KEY:+ required: falsejobs:build-linux-x64:runs-on: ubuntu-22.04@@ -127,7 +129,11 @@ jobs:# Change app name for beta and nightly buildsif [ "${{ inputs.channel }}" != "stable" ]; then- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.jsonchmod +x .github/scripts/rename-tauri-app.sh@@ -157,6 +163,7 @@ jobs:TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}AUTO_UPDATER_DISABLED: ${{ inputs.disable_updater && 'true' || 'false' }}+ JAN_SIGNING_KEY: ${{ secrets.JAN_SIGNING_KEY }}# Publish app## Artifacts, for dev and testdiff --git a/.github/workflows/template-tauri-build-linux-x64.yml b/.github/workflows/template-tauri-build-linux-x64.ymlindex 19ad7ad80..4c2a2204d 100644--- a/.github/workflows/template-tauri-build-linux-x64.yml+++ b/.github/workflows/template-tauri-build-linux-x64.yml@@ -44,6 +44,8 @@ on:required: falseTAURI_SIGNING_PRIVATE_KEY_PASSWORD:required: false+ JAN_SIGNING_KEY:+ required: falseoutputs:DEB_SIG:value: ${{ jobs.build-linux-x64.outputs.DEB_SIG }}@@ -148,7 +150,11 @@ jobs:# Change app name for beta and nightly buildsif [ "${{ inputs.channel }}" != "stable" ]; then- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.jsonchmod +x .github/scripts/rename-tauri-app.sh@@ -184,6 +190,7 @@ jobs:TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}AUTO_UPDATER_DISABLED: ${{ inputs.disable_updater && 'true' || 'false' }}+ JAN_SIGNING_KEY: ${{ secrets.JAN_SIGNING_KEY }}# Publish app## Artifacts, for dev and testdiff --git a/.github/workflows/template-tauri-build-macos-external.yml b/.github/workflows/template-tauri-build-macos-external.ymlindex 0357cc2a2..77d8f1e71 100644--- a/.github/workflows/template-tauri-build-macos-external.yml+++ b/.github/workflows/template-tauri-build-macos-external.yml@@ -79,7 +79,11 @@ jobs:ctoml ./src-tauri/Cargo.toml dependencies.tauri.features[] "devtools"if [ "${{ inputs.channel }}" != "stable" ]; then- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.jsonchmod +x .github/scripts/rename-tauri-app.sh.github/scripts/rename-tauri-app.sh ./src-tauri/tauri.conf.json ${{ inputs.channel }}diff --git a/.github/workflows/template-tauri-build-macos.yml b/.github/workflows/template-tauri-build-macos.ymlindex 9f8d46f6c..c1fdcaf19 100644--- a/.github/workflows/template-tauri-build-macos.yml+++ b/.github/workflows/template-tauri-build-macos.yml@@ -49,6 +49,8 @@ on:required: falseTAURI_SIGNING_PRIVATE_KEY_PASSWORD:required: false+ JAN_SIGNING_KEY:+ required: falseoutputs:MAC_UNIVERSAL_SIG:value: ${{ jobs.build-macos.outputs.MAC_UNIVERSAL_SIG }}@@ -133,7 +135,11 @@ jobs:# Change app name for beta and nightly buildsif [ "${{ inputs.channel }}" != "stable" ]; then- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.jsonchmod +x .github/scripts/rename-tauri-app.sh@@ -178,6 +184,7 @@ jobs:APPLE_API_KEY_PATH: /tmp/notary-key.p8TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ JAN_SIGNING_KEY: ${{ secrets.JAN_SIGNING_KEY }}# Publish appdiff --git a/.github/workflows/template-tauri-build-windows-x64-external.yml b/.github/workflows/template-tauri-build-windows-x64-external.ymlindex dbd5fd7eb..d6474410d 100644--- a/.github/workflows/template-tauri-build-windows-x64-external.yml+++ b/.github/workflows/template-tauri-build-windows-x64-external.yml@@ -113,7 +113,11 @@ jobs:sed -i "s/jan_build/$new_build_version/g" ./src-tauri/tauri.bundle.windows.nsis.templateif [ "${{ inputs.channel }}" != "stable" ]; then- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.json# Update product namediff --git a/.github/workflows/template-tauri-build-windows-x64.yml b/.github/workflows/template-tauri-build-windows-x64.ymlindex 166ad698f..ed897dee6 100644--- a/.github/workflows/template-tauri-build-windows-x64.yml+++ b/.github/workflows/template-tauri-build-windows-x64.yml@@ -49,6 +49,8 @@ on:required: falseTAURI_SIGNING_PRIVATE_KEY_PASSWORD:required: false+ JAN_SIGNING_KEY:+ required: falseoutputs:WIN_SIG:value: ${{ jobs.build-windows-x64.outputs.WIN_SIG }}@@ -175,8 +177,11 @@ jobs:# Change app name for beta and nightly buildsif [ "${{ inputs.channel }}" != "stable" ]; then- # Update updater endpoint- jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ if [[ "${{ inputs.channel }}" == "nightly" ]]; then+ jq '.plugins.updater.endpoints = ["https://apps-nightly.jan.ai/update-check", "https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ else+ jq '.plugins.updater.endpoints = ["https://delta.jan.ai/${{ inputs.channel }}/latest.json"]' ./src-tauri/tauri.conf.json > /tmp/tauri.conf.json+ fimv /tmp/tauri.conf.json ./src-tauri/tauri.conf.json# Update product name@@ -230,6 +235,7 @@ jobs:POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ JAN_SIGNING_KEY: ${{ secrets.JAN_SIGNING_KEY }}- name: Upload NSIS Installer Artifactuses: actions/upload-artifact@v4diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 08e2469c6..89cbbac9b 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -13,6 +13,8 @@ dependencies = ["flate2","futures-util","glob",+ "hex",+ "hmac","hostname","hyper 0.14.32","jan-utils",@@ -21,12 +23,14 @@ dependencies = ["log","nix","once_cell",+ "rand 0.8.5","reqwest 0.11.27","rfd","rmcp","serde","serde_json","serde_yaml",+ "sha2","sqlx","tar","tauri",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex fb6ee83af..3a76defd4 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -56,10 +56,13 @@ env = "1.0.1"fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }flate2 = "1.0"futures-util = "0.3.31"+hex = "0.4"+hmac = "0.12"hyper = { version = "0.14", features = ["server"] }jan-utils = { path = "./utils" }libloading = "0.8.7"log = "0.4"+rand = "0.8"rmcp = { version = "0.8.5", features = ["client","transport-sse-client",@@ -73,6 +76,7 @@ rmcp = { version = "0.8.5", features = [serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"serde_yaml = "0.9.34"+sha2 = "0.10"tar = "0.4"zip = "0.6"tauri-plugin-deep-link = { version = "2", optional = true }diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rsindex a20abd8dc..0ab6e0edc 100644--- a/src-tauri/src/core/mod.rs+++ b/src-tauri/src/core/mod.rs@@ -8,3 +8,6 @@ pub mod setup;pub mod state;pub mod system;pub mod threads;++#[cfg(not(any(target_os = "android", target_os = "ios")))]+pub mod updater;diff --git a/src-tauri/src/core/updater/commands.rs b/src-tauri/src/core/updater/commands.rsnew file mode 100644index 000000000..5fbec82df--- /dev/null+++ b/src-tauri/src/core/updater/commands.rs@@ -0,0 +1,83 @@+/**+ * Tauri commands for custom updater with HMAC request signing+ *+ * Convention: First endpoint in tauri.conf.json uses HMAC signing, rest are fallbacks+ */+use super::custom_updater::{CustomUpdater, UpdateInfo};+use tauri::{command, AppHandle};++/// Check for updates using endpoints from tauri.conf.json+/// First endpoint uses HMAC request signing, remaining endpoints are fallbacks+#[command]+pub async fn check_for_app_updates(+ app: AppHandle,+ nonce_seed: String,+ current_version: String,+) -> Result<Option<UpdateInfo>, String> {+ // Get endpoints from tauri config+ let endpoints = get_updater_endpoints(&app);++ if endpoints.is_empty() {+ return Err("No updater endpoints configured in tauri.conf.json".to_string());+ }++ let updater = CustomUpdater::new().map_err(|e| e.to_string())?;++ let update_info = updater+ .check_for_updates(endpoints, &nonce_seed, ¤t_version)+ .await+ .map_err(|e| e.to_string())?;++ // Only return update info if the version is actually newer+ if let Some(ref info) = update_info {+ if updater.is_update_available(¤t_version, &info.version) {+ log::info!(+ "Update available: current {} -> latest {}",+ current_version,+ info.version+ );+ return Ok(update_info);+ } else {+ log::info!(+ "No update needed: current {} is up to date with latest {}",+ current_version,+ info.version+ );+ return Ok(None);+ }+ }++ Ok(None)+}++/// Get updater endpoints from tauri config+fn get_updater_endpoints(app: &AppHandle) -> Vec<String> {+ // Try to get endpoints from tauri config+ // The config structure is: plugins.updater.endpoints+ let config = app.config();++ if let Some(plugins) = &config.plugins.0.get("updater") {+ if let Some(endpoints) = plugins.get("endpoints") {+ if let Some(arr) = endpoints.as_array() {+ return arr+ .iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect();+ }+ }+ }++ // Return empty if no endpoints found+ Vec::new()+}++/// Check if update is available by comparing versions+#[command]+pub fn is_update_available(current_version: String, latest_version: String) -> bool {+ let updater = match CustomUpdater::new() {+ Ok(u) => u,+ Err(_) => return false,+ };+ updater.is_update_available(¤t_version, &latest_version)+}+diff --git a/src-tauri/src/core/updater/custom_updater.rs b/src-tauri/src/core/updater/custom_updater.rsnew file mode 100644index 000000000..5c3ccf914--- /dev/null+++ b/src-tauri/src/core/updater/custom_updater.rs@@ -0,0 +1,266 @@+/**+ * Custom Updater for Jan with HMAC request signing+ *+ * This module provides a custom update checker that:+ * 1. Reads endpoints from tauri.conf.json (plugins.updater.endpoints)+ * 2. First endpoint is treated as PRIMARY - uses HMAC request signing+ * 3. Remaining endpoints are FALLBACK - no signing needed+ *+ * Convention: The first endpoint in the list should be the signed endpoint+ * (e.g., https://apps.jan.ai/update-check)+ */+use super::hmac_client::SignedRequestHeaders;+use reqwest::Client;+use serde::{Deserialize, Serialize};+use std::time::Duration;+use thiserror::Error;++/// Secret key for HMAC signature+/// - In CI: Set JAN_SIGNING_KEY environment variable at build time+/// - In local dev: Falls back to a test key+const SECRET_KEY: &str = match option_env!("JAN_SIGNING_KEY") {+ Some(key) => key,+ None => "local-dev-test-key-not-for-production",+};++/// Timeout for HTTP requests+const REQUEST_TIMEOUT_SECS: u64 = 30;++#[derive(Debug, Error)]+pub enum UpdateError {+ #[error("HTTP request failed: {0}")]+ RequestFailed(#[from] reqwest::Error),++ #[error("Failed to parse update response: {0}")]+ ParseError(String),++ #[error("All endpoints failed")]+ AllEndpointsFailed,++ #[error("Invalid response from server: {0}")]+ InvalidResponse(String),++ #[error("No endpoints configured")]+ NoEndpointsConfigured,+}++/// Update information returned by the update check endpoint+/// Compatible with Tauri's updater format+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UpdateInfo {+ pub version: String,+ #[serde(default)]+ pub notes: Option<String>,+ #[serde(default)]+ pub pub_date: Option<String>,+ #[serde(default)]+ pub platforms: Option<serde_json::Value>,+ /// URL to download the update+ #[serde(default)]+ pub url: Option<String>,+ /// Signature for verifying the update+ #[serde(default)]+ pub signature: Option<String>,+}++/// Custom updater client+pub struct CustomUpdater {+ client: Client,+ secret_key: String,+}++impl CustomUpdater {+ /// Create a new custom updater+ pub fn new() -> Result<Self, UpdateError> {+ let client = Client::builder()+ .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))+ .build()?;++ Ok(Self {+ client,+ secret_key: SECRET_KEY.to_string(),+ })+ }++ /// Build User-Agent header: Jan/{version} ({os}; {arch})+ fn build_user_agent(app_version: &str) -> String {+ let os = std::env::consts::OS;+ let arch = std::env::consts::ARCH;+ format!("Jan/{} ({}; {})", app_version, os, arch)+ }++ /// Check for updates using endpoints list+ /// First endpoint uses HMAC signing, rest are fallbacks without signing+ pub async fn check_for_updates(+ &self,+ endpoints: Vec<String>,+ nonce_seed: &str,+ current_version: &str,+ ) -> Result<Option<UpdateInfo>, UpdateError> {+ if endpoints.is_empty() {+ return Err(UpdateError::NoEndpointsConfigured);+ }++ log::info!(+ "Checking for updates (current version: {}, {} endpoints configured)",+ current_version,+ endpoints.len()+ );++ let mut last_error: Option<UpdateError> = None;++ for (index, endpoint) in endpoints.iter().enumerate() {+ let is_primary = index == 0;++ let result = if is_primary {+ // First endpoint: use HMAC signing+ log::info!("Trying primary endpoint with signing: {}", endpoint);+ self.check_with_signing(endpoint, nonce_seed, current_version)+ .await+ } else {+ // Fallback endpoints: no signing+ log::info!("Trying fallback endpoint: {}", endpoint);+ self.check_without_signing(endpoint, current_version).await+ };++ match result {+ Ok(info) => {+ log::info!(+ "Successfully fetched update info from endpoint {}: version {}",+ endpoint,+ info.version+ );+ return Ok(Some(info));+ }+ Err(e) => {+ log::warn!("Endpoint {} failed: {}", endpoint, e);+ last_error = Some(e);+ // Continue to next endpoint+ }+ }+ }++ // All endpoints failed+ log::error!("All {} endpoints failed", endpoints.len());+ Err(last_error.unwrap_or(UpdateError::AllEndpointsFailed))+ }++ /// Check endpoint with HMAC request signing+ async fn check_with_signing(+ &self,+ endpoint: &str,+ nonce_seed: &str,+ app_version: &str,+ ) -> Result<UpdateInfo, UpdateError> {+ // Generate signed request headers+ let headers = SignedRequestHeaders::new(&self.secret_key, nonce_seed, app_version);++ // Build request with security headers+ let mut request = self.client.get(endpoint);++ for (key, value) in headers.to_header_pairs() {+ request = request.header(key, value);+ }++ request = request+ .header("Accept", "application/json")+ .header("User-Agent", Self::build_user_agent(app_version));++ // Send request+ let response = request.send().await?;++ // Check response status+ if !response.status().is_success() {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ return Err(UpdateError::InvalidResponse(format!(+ "Status {}: {}",+ status, body+ )));+ }++ // Parse response+ let update_info: UpdateInfo = response+ .json()+ .await+ .map_err(|e| UpdateError::ParseError(e.to_string()))?;++ Ok(update_info)+ }++ /// Check endpoint without signing (for fallback endpoints)+ async fn check_without_signing(&self, endpoint: &str, app_version: &str) -> Result<UpdateInfo, UpdateError> {+ let response = self+ .client+ .get(endpoint)+ .header("Accept", "application/json")+ .header("User-Agent", Self::build_user_agent(app_version))+ .send()+ .await?;++ if !response.status().is_success() {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ return Err(UpdateError::InvalidResponse(format!(+ "Status {}: {}",+ status, body+ )));+ }++ let update_info: UpdateInfo = response+ .json()+ .await+ .map_err(|e| UpdateError::ParseError(e.to_string()))?;++ Ok(update_info)+ }++ /// Compare versions to check if update is available+ pub fn is_update_available(&self, current: &str, latest: &str) -> bool {+ let current = current.trim_start_matches('v');+ let latest = latest.trim_start_matches('v');++ let current_parts: Vec<u32> = current+ .split('.')+ .filter_map(|s| s.parse().ok())+ .collect();+ let latest_parts: Vec<u32> = latest.split('.').filter_map(|s| s.parse().ok()).collect();++ for i in 0..std::cmp::max(current_parts.len(), latest_parts.len()) {+ let current_part = current_parts.get(i).unwrap_or(&0);+ let latest_part = latest_parts.get(i).unwrap_or(&0);++ if latest_part > current_part {+ return true;+ } else if latest_part < current_part {+ return false;+ }+ }++ false+ }+}++impl Default for CustomUpdater {+ fn default() -> Self {+ Self::new().expect("Failed to create default CustomUpdater")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_version_comparison() {+ let updater = CustomUpdater::new().unwrap();++ assert!(updater.is_update_available("1.0.0", "1.0.1"));+ assert!(updater.is_update_available("1.0.0", "1.1.0"));+ assert!(updater.is_update_available("1.0.0", "2.0.0"));+ assert!(!updater.is_update_available("1.0.0", "1.0.0"));+ assert!(!updater.is_update_available("1.0.1", "1.0.0"));+ assert!(updater.is_update_available("v1.0.0", "v1.0.1"));+ }+}+diff --git a/src-tauri/src/core/updater/hmac_client.rs b/src-tauri/src/core/updater/hmac_client.rsnew file mode 100644index 000000000..35d50153c--- /dev/null+++ b/src-tauri/src/core/updater/hmac_client.rs@@ -0,0 +1,130 @@+/**+ * HMAC client for secure update check requests+ * Provides request signing to verify request integrity and prevent tampering+ */+use hmac::{Hmac, Mac};+use rand::Rng;+use sha2::Sha256;+use std::time::{SystemTime, UNIX_EPOCH};++type HmacSha256 = Hmac<Sha256>;++/// Header names for request signing+pub struct HeaderNames;++impl HeaderNames {+ /// Seed value for nonce generation (part of signature computation)+ pub const NONCE_SEED: &'static str = "X-Client-Session";+ /// HMAC signature for request verification+ pub const SIGNATURE: &'static str = "X-Request-Token";+ /// Request timestamp (for replay protection)+ pub const TIMESTAMP: &'static str = "X-Request-Time";+ /// Random nonce (for replay protection)+ pub const NONCE: &'static str = "X-Request-Id";+ /// Current app version being checked+ pub const VERSION: &'static str = "X-Client-Version";+}++/// Generate a cryptographically secure nonce (64 hex characters = 32 bytes)+pub fn generate_nonce() -> String {+ let mut rng = rand::thread_rng();+ let bytes: [u8; 32] = rng.gen();+ hex::encode(bytes)+}++/// Get current Unix timestamp as string+pub fn get_timestamp() -> String {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("Time went backwards")+ .as_secs()+ .to_string()+}++/// Generate HMAC-SHA256 signature for request verification+/// Message format: "{nonce_seed}:{timestamp}:{nonce}"+pub fn generate_signature(secret_key: &str, nonce_seed: &str, timestamp: &str, nonce: &str) -> String {+ let message = format!("{}:{}:{}", nonce_seed, timestamp, nonce);++ let mut mac =+ HmacSha256::new_from_slice(secret_key.as_bytes()).expect("HMAC can take key of any size");+ mac.update(message.as_bytes());++ hex::encode(mac.finalize().into_bytes())+}++/// Request signing headers for update checks+#[derive(Debug, Clone)]+pub struct SignedRequestHeaders {+ pub nonce_seed: String,+ pub signature: String,+ pub timestamp: String,+ pub nonce: String,+ pub version: String,+}++impl SignedRequestHeaders {+ /// Generate signed headers for an update check request+ pub fn new(secret_key: &str, nonce_seed: &str, app_version: &str) -> Self {+ let timestamp = get_timestamp();+ let nonce = generate_nonce();+ let signature = generate_signature(secret_key, nonce_seed, ×tamp, &nonce);++ Self {+ nonce_seed: nonce_seed.to_string(),+ signature,+ timestamp,+ nonce,+ version: app_version.to_string(),+ }+ }++ /// Convert to HTTP header key-value pairs+ pub fn to_header_pairs(&self) -> Vec<(&'static str, String)> {+ vec![+ (HeaderNames::NONCE_SEED, self.nonce_seed.clone()),+ (HeaderNames::SIGNATURE, self.signature.clone()),+ (HeaderNames::TIMESTAMP, self.timestamp.clone()),+ (HeaderNames::NONCE, self.nonce.clone()),+ (HeaderNames::VERSION, self.version.clone()),+ ]+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_signature_generation() {+ // Test with known values+ let signature = generate_signature(+ "your-super-secret-key-change-in-production-minimum-32-chars",+ "test-seed-123",+ "1704067200",+ "abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234",+ );++ // Signature should be 64 hex characters (SHA256)+ assert_eq!(signature.len(), 64);+ }++ #[test]+ fn test_nonce_generation() {+ let nonce = generate_nonce();+ // Nonce should be 64 hex characters (32 bytes)+ assert_eq!(nonce.len(), 64);+ assert!(nonce.chars().all(|c| c.is_ascii_hexdigit()));+ }++ #[test]+ fn test_signed_headers_generation() {+ let headers = SignedRequestHeaders::new("test-secret", "seed-123", "1.0.0");++ assert_eq!(headers.nonce_seed, "seed-123");+ assert_eq!(headers.version, "1.0.0");+ assert_eq!(headers.signature.len(), 64);+ assert_eq!(headers.nonce.len(), 64);+ assert!(!headers.timestamp.is_empty());+ }+}diff --git a/src-tauri/src/core/updater/mod.rs b/src-tauri/src/core/updater/mod.rsnew file mode 100644index 000000000..0d5453ddd--- /dev/null+++ b/src-tauri/src/core/updater/mod.rs@@ -0,0 +1,3 @@+pub mod commands;+pub mod custom_updater;+pub mod hmac_client;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex b60bf95b7..cc17eb1d8 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -46,74 +46,150 @@ pub fn run() {app_builder = app_builder.plugin(tauri_plugin_hardware::init());}+ // Desktop: include updater commands+ #[cfg(not(any(target_os = "android", target_os = "ios")))]+ let app_builder = app_builder.invoke_handler(tauri::generate_handler![+ // FS commands - Deperecate soon+ core::filesystem::commands::join_path,+ core::filesystem::commands::mkdir,+ core::filesystem::commands::exists_sync,+ core::filesystem::commands::readdir_sync,+ core::filesystem::commands::read_file_sync,+ core::filesystem::commands::rm,+ core::filesystem::commands::mv,+ core::filesystem::commands::file_stat,+ core::filesystem::commands::write_file_sync,+ core::filesystem::commands::write_yaml,+ core::filesystem::commands::read_yaml,+ core::filesystem::commands::decompress,+ core::filesystem::commands::open_dialog,+ core::filesystem::commands::save_dialog,+ // App configuration commands+ core::app::commands::get_app_configurations,+ core::app::commands::get_user_home_path,+ core::app::commands::update_app_configuration,+ core::app::commands::get_jan_data_folder_path,+ core::app::commands::get_configuration_file_path,+ core::app::commands::default_data_folder_path,+ core::app::commands::change_app_data_folder,+ core::app::commands::app_token,+ // Extension commands+ core::extensions::commands::get_jan_extensions_path,+ core::extensions::commands::install_extensions,+ core::extensions::commands::get_active_extensions,+ // System commands+ core::system::commands::relaunch,+ core::system::commands::open_app_directory,+ core::system::commands::open_file_explorer,+ core::system::commands::factory_reset,+ core::system::commands::read_logs,+ core::system::commands::is_library_available,+ // Server commands+ core::server::commands::start_server,+ core::server::commands::stop_server,+ core::server::commands::get_server_status,+ // MCP commands+ core::mcp::commands::get_tools,+ core::mcp::commands::call_tool,+ core::mcp::commands::cancel_tool_call,+ core::mcp::commands::restart_mcp_servers,+ core::mcp::commands::get_connected_servers,+ core::mcp::commands::save_mcp_configs,+ core::mcp::commands::get_mcp_configs,+ core::mcp::commands::activate_mcp_server,+ core::mcp::commands::deactivate_mcp_server,+ core::mcp::commands::check_jan_browser_extension_connected,+ // Threads+ core::threads::commands::list_threads,+ core::threads::commands::create_thread,+ core::threads::commands::modify_thread,+ core::threads::commands::delete_thread,+ core::threads::commands::list_messages,+ core::threads::commands::create_message,+ core::threads::commands::modify_message,+ core::threads::commands::delete_message,+ core::threads::commands::get_thread_assistant,+ core::threads::commands::create_thread_assistant,+ core::threads::commands::modify_thread_assistant,+ // Download+ core::downloads::commands::download_files,+ core::downloads::commands::cancel_download_task,+ // Custom updater commands (desktop only)+ core::updater::commands::check_for_app_updates,+ core::updater::commands::is_update_available,+ ]);++ // Mobile: no updater commands+ #[cfg(any(target_os = "android", target_os = "ios"))]+ let app_builder = app_builder.invoke_handler(tauri::generate_handler![+ // FS commands - Deperecate soon+ core::filesystem::commands::join_path,+ core::filesystem::commands::mkdir,+ core::filesystem::commands::exists_sync,+ core::filesystem::commands::readdir_sync,+ core::filesystem::commands::read_file_sync,+ core::filesystem::commands::rm,+ core::filesystem::commands::mv,+ core::filesystem::commands::file_stat,+ core::filesystem::commands::write_file_sync,+ core::filesystem::commands::write_yaml,+ core::filesystem::commands::read_yaml,+ core::filesystem::commands::decompress,+ core::filesystem::commands::open_dialog,+ core::filesystem::commands::save_dialog,+ // App configuration commands+ core::app::commands::get_app_configurations,+ core::app::commands::get_user_home_path,+ core::app::commands::update_app_configuration,+ core::app::commands::get_jan_data_folder_path,+ core::app::commands::get_configuration_file_path,+ core::app::commands::default_data_folder_path,+ core::app::commands::change_app_data_folder,+ core::app::commands::app_token,+ // Extension commands+ core::extensions::commands::get_jan_extensions_path,+ core::extensions::commands::install_extensions,+ core::extensions::commands::get_active_extensions,+ // System commands+ core::system::commands::relaunch,+ core::system::commands::open_app_directory,+ core::system::commands::open_file_explorer,+ core::system::commands::factory_reset,+ core::system::commands::read_logs,+ core::system::commands::is_library_available,+ // Server commands+ core::server::commands::start_server,+ core::server::commands::stop_server,+ core::server::commands::get_server_status,+ // MCP commands+ core::mcp::commands::get_tools,+ core::mcp::commands::call_tool,+ core::mcp::commands::cancel_tool_call,+ core::mcp::commands::restart_mcp_servers,+ core::mcp::commands::get_connected_servers,+ core::mcp::commands::save_mcp_configs,+ core::mcp::commands::get_mcp_configs,+ core::mcp::commands::activate_mcp_server,+ core::mcp::commands::deactivate_mcp_server,+ core::mcp::commands::check_jan_browser_extension_connected,+ // Threads+ core::threads::commands::list_threads,+ core::threads::commands::create_thread,+ core::threads::commands::modify_thread,+ core::threads::commands::delete_thread,+ core::threads::commands::list_messages,+ core::threads::commands::create_message,+ core::threads::commands::modify_message,+ core::threads::commands::delete_message,+ core::threads::commands::get_thread_assistant,+ core::threads::commands::create_thread_assistant,+ core::threads::commands::modify_thread_assistant,+ // Download+ core::downloads::commands::download_files,+ core::downloads::commands::cancel_download_task,+ ]);+let app = app_builder- .invoke_handler(tauri::generate_handler![- // FS commands - Deperecate soon- core::filesystem::commands::join_path,- core::filesystem::commands::mkdir,- core::filesystem::commands::exists_sync,- core::filesystem::commands::readdir_sync,- core::filesystem::commands::read_file_sync,- core::filesystem::commands::rm,- core::filesystem::commands::mv,- core::filesystem::commands::file_stat,- core::filesystem::commands::write_file_sync,- core::filesystem::commands::write_yaml,- core::filesystem::commands::read_yaml,- core::filesystem::commands::decompress,- core::filesystem::commands::open_dialog,- core::filesystem::commands::save_dialog,- // App configuration commands- core::app::commands::get_app_configurations,- core::app::commands::get_user_home_path,- core::app::commands::update_app_configuration,- core::app::commands::get_jan_data_folder_path,- core::app::commands::get_configuration_file_path,- core::app::commands::default_data_folder_path,- core::app::commands::change_app_data_folder,- core::app::commands::app_token,- // Extension commands- core::extensions::commands::get_jan_extensions_path,- core::extensions::commands::install_extensions,- core::extensions::commands::get_active_extensions,- // System commands- core::system::commands::relaunch,- core::system::commands::open_app_directory,- core::system::commands::open_file_explorer,- core::system::commands::factory_reset,- core::system::commands::read_logs,- core::system::commands::is_library_available,- // Server commands- core::server::commands::start_server,- core::server::commands::stop_server,- core::server::commands::get_server_status,- // MCP commands- core::mcp::commands::get_tools,- core::mcp::commands::call_tool,- core::mcp::commands::cancel_tool_call,- core::mcp::commands::restart_mcp_servers,- core::mcp::commands::get_connected_servers,- core::mcp::commands::save_mcp_configs,- core::mcp::commands::get_mcp_configs,- core::mcp::commands::activate_mcp_server,- core::mcp::commands::deactivate_mcp_server,- core::mcp::commands::check_jan_browser_extension_connected,- // Threads- core::threads::commands::list_threads,- core::threads::commands::create_thread,- core::threads::commands::modify_thread,- core::threads::commands::delete_thread,- core::threads::commands::list_messages,- core::threads::commands::create_message,- core::threads::commands::modify_message,- core::threads::commands::delete_message,- core::threads::commands::get_thread_assistant,- core::threads::commands::create_thread_assistant,- core::threads::commands::modify_thread_assistant,- // Download- core::downloads::commands::download_files,- core::downloads::commands::cancel_download_task,- ]).manage(AppState {app_token: Some(generate_app_token()),mcp_servers: Arc::new(Mutex::new(HashMap::new())),diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 8947adcd1..27cffdcb9 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -72,6 +72,7 @@"updater": {"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDJFNDEzMEVCMUEzNUFENDQKUldSRXJUVWE2ekJCTGc1Mm1BVXgrWmtES3huUlBFR0lCdG5qbWFvMzgyNDhGN3VTTko5Q1NtTW0K","endpoints": [+ "https://apps.jan.ai/update-check","https://github.com/janhq/jan/releases/latest/download/latest.json"],"windows": {diff --git a/web-app/package.json b/web-app/package.jsonindex 3ac563703..bd87f937a 100644--- a/web-app/package.json+++ b/web-app/package.json@@ -49,6 +49,7 @@"@tauri-apps/plugin-http": "2.5.0","@tauri-apps/plugin-opener": "2.5.2","@tauri-apps/plugin-os": "2.2.1",+ "@tauri-apps/plugin-store": "^2.4.2","@tauri-apps/plugin-updater": "2.8.1","@types/react-syntax-highlighter": "15.5.13","@types/uuid": "10.0.0",diff --git a/web-app/src/services/updater/tauri.ts b/web-app/src/services/updater/tauri.tsindex a84951e7e..29a0b8e99 100644--- a/web-app/src/services/updater/tauri.ts+++ b/web-app/src/services/updater/tauri.ts@@ -1,14 +1,100 @@/*** Tauri Updater Service - Desktop implementation+ *+ * This service uses a custom update check with HMAC request signing:+ * 1. First tries primary endpoint (from tauri.conf.json) with signed request+ * 2. Falls back to other endpoints without signing if primary fails+ * 3. Uses Tauri's built-in updater for download/install (with signature verification)*/import { check, Update } from '@tauri-apps/plugin-updater'+import { invoke } from '@tauri-apps/api/core'+import { load } from '@tauri-apps/plugin-store'import type { UpdateInfo, UpdateProgressEvent } from './types'import { DefaultUpdaterService } from './default'+// Store key for nonce seed+const STORE_NAME = 'updater.json'+const NONCE_SEED_KEY = 'nonce_seed'++// Cache nonce seed in memory to avoid repeated store reads+let cachedNonceSeed: string | null = null++// Get or generate nonce seed for request signing (persisted in app data folder)+async function getNonceSeed(): Promise<string> {+ // Return cached value if available+ if (cachedNonceSeed) {+ return cachedNonceSeed+ }++ try {+ const store = await load(STORE_NAME, { autoSave: true, defaults: {} })+ let nonceSeed = await store.get<string>(NONCE_SEED_KEY)++ if (!nonceSeed) {+ nonceSeed = crypto.randomUUID()+ await store.set(NONCE_SEED_KEY, nonceSeed)+ await store.save()+ }++ cachedNonceSeed = nonceSeed+ return nonceSeed+ } catch (error) {+ // Fallback to random seed if store fails+ console.warn('Failed to access store for nonce seed, using temporary seed:', error)+ const tempSeed = crypto.randomUUID()+ cachedNonceSeed = tempSeed+ return tempSeed+ }+}++// Get current app version+async function getCurrentVersion(): Promise<string> {+ try {+ const { getVersion } = await import('@tauri-apps/api/app')+ return await getVersion()+ } catch {+ return '0.0.0'+ }+}+export class TauriUpdaterService extends DefaultUpdaterService {+ /**+ * Check for updates using custom signed request for primary endpoint+ * Falls back to standard Tauri updater if custom check fails+ */async check(): Promise<UpdateInfo | null> {try {+ const nonceSeed = await getNonceSeed()+ const currentVersion = await getCurrentVersion()++ // Try custom updater with request signing first+ try {+ const customUpdate = await invoke<{+ version: string+ notes?: string+ pub_date?: string+ url?: string+ signature?: string+ } | null>('check_for_app_updates', {+ nonceSeed,+ currentVersion,+ })++ if (customUpdate) {+ console.log('Update found via custom updater:', customUpdate.version)+ return {+ version: customUpdate.version,+ date: customUpdate.pub_date,+ body: customUpdate.notes,+ signature: customUpdate.signature,+ }+ }+ } catch (customError) {+ console.warn('Custom updater check failed, falling back to standard Tauri updater:', customError)+ }++ // Fallback to standard Tauri updater (uses tauri.conf.json endpoints)const update: Update | null = await check()if (!update) return null@@ -61,3 +147,4 @@ export class TauriUpdaterService extends DefaultUpdaterService {}}}+