tauri_plugin_ota_updater/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::{
    borrow::Cow,
    cell::OnceCell,
    collections::HashMap,
    io::{Cursor, Read},
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use base64::Engine;
use serde::{Deserialize, Deserializer, Serialize};
use tar::Archive;
use tauri::{
    plugin::{Builder, TauriPlugin},
    utils::assets::{AssetKey, CspHash},
    App, AppHandle, Assets, Context, Manager, Runtime, State, Url,
};

mod error;

pub use error::{Error, Result};

struct PendingUpdate<R: Runtime>(tauri::async_runtime::Mutex<Option<Update<R>>>);

const DEFAULT_CHANNEL: &str = "over-the-air";
const CHANNEL_PREFIX: &str = "over-the-air-";

/// Access to the ota updater APIs.
pub struct OTAUpdater<R: Runtime> {
    cache_path: PathBuf,
    config: Arc<tauri::async_runtime::Mutex<Config>>,
    manifest: Arc<tauri::async_runtime::Mutex<Manifest>>,
    assets: Arc<Mutex<HashMap<AssetKey, Vec<u8>>>>,
    embedded_assets: Arc<Mutex<Option<Box<dyn Assets<R>>>>>,
}

impl<R: Runtime> Clone for OTAUpdater<R> {
    fn clone(&self) -> Self {
        Self {
            cache_path: self.cache_path.clone(),
            config: self.config.clone(),
            manifest: self.manifest.clone(),
            assets: self.assets.clone(),
            embedded_assets: self.embedded_assets.clone(),
        }
    }
}

fn manifest_path(cache_path: &Path) -> PathBuf {
    cache_path.join("ota-updates-manifest.json")
}

fn latest_update_archive_path(cache_path: &Path) -> PathBuf {
    cache_path.join("latest-update.tar.gz")
}

#[derive(Deserialize)]
struct UpdateResponse {
    version: String,
    notes: String,
    pub_date: String,
    url: Url,
}

impl<R: Runtime> OTAUpdater<R> {
    pub async fn check_for_updates(&self) -> Result<Option<Update<R>>> {
        let current_manifest_id = self.manifest.lock().await.id.clone();
        let manifest_update_url = self
            .config
            .lock()
            .await
            .update_url_for(&current_manifest_id, "manifest");

        // ideally we'd be able to use the JSON file updater mode here
        // so we'd get the download URL for all assets in the release
        // TODO: needs a cloud CDN endpoint :)
        let update = reqwest::get(manifest_update_url)
            .await?
            .json::<UpdateResponse>()
            .await?;

        let manifest = reqwest::get(update.url).await?.json::<Manifest>().await?;

        let current_manifest_id = self.manifest.lock().await.id.clone();
        if manifest.id != current_manifest_id {
            let latest_dist = reqwest::get(
                self.config
                    .lock()
                    .await
                    .latest_url_for_filename("ota-dist.tar.gz"),
            )
            .await?
            .bytes()
            .await?
            .to_vec();

            let pub_key_decoded = base64_to_string(&self.config.lock().await.pubkey)?;
            let public_key = minisign_verify::PublicKey::decode(&pub_key_decoded)
                .map_err(Error::InvalidPublicKey)?;

            let dist_signature_base64_decoded = base64_to_string(&manifest.archive_signature)?;
            let dist_signature = minisign_verify::Signature::decode(&dist_signature_base64_decoded)
                .map_err(Error::InvalidSignature)?;

            public_key
                .verify(&latest_dist, &dist_signature, false)
                .map_err(Error::InvalidSignature)?;

            let archive = tar::Archive::new(Cursor::new(&latest_dist));

            let update_assets =
                load_assets(archive, &manifest, &public_key, &self.cache_path).await?;

            return Ok(Some(Update {
                version: update.version,
                notes: update.notes,
                pub_date: update.pub_date,
                archive: latest_dist,
                manifest,
                assets: update_assets,
                updater: self.clone(),
            }));
        }

        Ok(None)
    }
}

/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the ota-updater APIs.
pub trait OTAUpdaterExt<R: Runtime> {
    fn ota_updater(&self) -> &OTAUpdater<R>;
}

impl<R: Runtime, T: Manager<R>> crate::OTAUpdaterExt<R> for T {
    fn ota_updater(&self) -> &OTAUpdater<R> {
        self.state::<OTAUpdater<R>>().inner()
    }
}

pub struct Update<R: Runtime> {
    pub version: String,
    pub notes: String,
    pub pub_date: String,
    updater: OTAUpdater<R>,
    archive: Vec<u8>,
    manifest: Manifest,
    assets: HashMap<AssetKey, Vec<u8>>,
}

impl<R: Runtime> Update<R> {
    pub async fn apply(&self) -> Result<()> {
        *self.updater.assets.lock().unwrap() = self.assets.clone();
        std::fs::write(
            manifest_path(&self.updater.cache_path),
            serde_json::to_string(&self.manifest)?,
        )?;
        *self.updater.manifest.lock().await = self.manifest.clone();
        std::fs::write(
            latest_update_archive_path(&self.updater.cache_path),
            &self.archive,
        )?;

        Ok(())
    }
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Manifest {
    id: String,
    archive_signature: String,
    files: HashMap<PathBuf, ManifestFile>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ManifestFile {
    signature: String,
}

pub struct OTAAssets<R: Runtime> {
    embedded_assets: OnceCell<Box<dyn Assets<R>>>,
    assets: Arc<Mutex<HashMap<AssetKey, Vec<u8>>>>,
    csp_hashes: Vec<CspHash<'static>>,
}

// we make sure assets are initialized once early
unsafe impl<R: Runtime> Sync for OTAAssets<R> {}

impl<R: Runtime> Assets<R> for OTAAssets<R> {
    fn setup(&self, app: &App<R>) {
        let ota = app.state::<OTAUpdater<R>>();
        self.embedded_assets.get_or_init(|| {
            let assets = ota.embedded_assets.lock().unwrap().take().unwrap();
            assets.setup(app);
            assets
        });

        *self.assets.lock().unwrap() = {
            if let Ok(archive_bytes) = std::fs::read(latest_update_archive_path(&ota.cache_path)) {
                let load_assets_fut = async {
                    let pub_key_decoded = base64_to_string(&ota.config.lock().await.pubkey)?;
                    let public_key = minisign_verify::PublicKey::decode(&pub_key_decoded)
                        .map_err(Error::InvalidPublicKey)?;

                    load_assets(
                        tar::Archive::new(Cursor::new(archive_bytes)),
                        &*ota.manifest.lock().await,
                        &public_key,
                        &ota.cache_path,
                    )
                    .await
                };
                match tauri::async_runtime::block_on(load_assets_fut) {
                    Ok(assets) => assets,
                    Err(_e) => {
                        #[cfg(debug_assertions)]
                        eprintln!("failed to load assets: {_e}");
                        // failed to load assets (usually means an invalid signature was found)
                        // let's use an empty asset map so we automatically fallback to the embedded assets
                        HashMap::new()
                    }
                }
            } else {
                // no update, let's use an empty asset map so we automatically fallback to the embedded assets
                HashMap::new()
            }
        };
    }

    fn csp_hashes(&self, _html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
        Box::new(self.csp_hashes.iter().copied())
    }

    fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
        self.assets
            .lock()
            .unwrap()
            .get(key)
            .map(|b| Cow::Owned(b.clone()))
            // if we fail to load assets (invalid signature, not uploaded yet or missing file)
            // we'll fallback to the embedded assets
            .or_else(|| self.embedded_assets.get().unwrap().get(key))
    }

    fn iter(&self) -> Box<dyn Iterator<Item = (Cow<'_, str>, Cow<'_, [u8]>)> + '_> {
        Box::new(
            self.assets
                .lock()
                .unwrap()
                .clone()
                .into_iter()
                .map(|(k, v)| (Cow::Owned(k.as_ref().to_string()), Cow::Owned(v))),
        )
    }
}

#[derive(Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Config {
    pub cdn_host: Option<String>,
    pub org_slug: String,
    pub app_slug: String,
    pub pubkey: String,
    #[serde(deserialize_with = "channel_deserializer", default)]
    pub channel: Option<String>,
}

fn channel_deserializer<'de, D>(deserializer: D) -> std::result::Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let s = Option::<String>::deserialize(deserializer)?;

    Ok(match s.as_deref() {
        Some(DEFAULT_CHANNEL) => None,
        Some(c) => c
            .strip_prefix(CHANNEL_PREFIX)
            .map(ToString::to_string)
            .or(s),
        None => None,
    })
}

impl Config {
    fn update_url_for(&self, current_version: &str, update_platform: &str) -> Url {
        format!(
            "https://{}/update/{}/{}/{update_platform}/{current_version}?channel={}",
            self.cdn_host.as_deref().unwrap_or("cdn.crabnebula.app"),
            self.org_slug,
            self.app_slug,
            self.channel.as_deref().unwrap_or(DEFAULT_CHANNEL)
        )
        .parse()
        .expect("invalid URL")
    }

    fn latest_url_for_filename(&self, filename: &str) -> Url {
        format!(
            "https://{}/download/{}/{}/latest/{filename}?channel={}",
            self.cdn_host.as_deref().unwrap_or("cdn.crabnebula.app"),
            self.org_slug,
            self.app_slug,
            self.channel.as_deref().unwrap_or(DEFAULT_CHANNEL)
        )
        .parse()
        .expect("invalid URL")
    }
}

#[tauri::command]
async fn set_channel<R: Runtime>(
    _app: AppHandle<R>,
    ota: State<'_, OTAUpdater<R>>,
    channel: Option<String>,
) -> Result<()> {
    ota.config.lock().await.channel = channel;
    Ok(())
}

#[tauri::command]
async fn check_for_updates<R: Runtime>(
    app: AppHandle<R>,
    ota: State<'_, OTAUpdater<R>>,
) -> Result<bool> {
    if let Some(update) = ota.check_for_updates().await? {
        if let Some(pending) = app.try_state::<PendingUpdate<R>>() {
            pending.0.lock().await.replace(update);
        } else {
            app.manage(PendingUpdate(tauri::async_runtime::Mutex::new(Some(
                update,
            ))));
        }
        Ok(true)
    } else {
        Ok(false)
    }
}

#[tauri::command]
async fn apply_update<R: Runtime>(app: AppHandle<R>) -> Result<()> {
    if let Some(update) = app.try_state::<PendingUpdate<R>>() {
        let mut pending = update.0.lock().await;
        if let Some(update) = &*pending {
            update.apply().await?;
            *pending = None;
        }
    }
    Ok(())
}

/// Initializes the plugin.
pub fn init<R: Runtime>(mut context: Context<R>) -> (TauriPlugin<R, Config>, Context<R>) {
    let assets = Arc::new(Mutex::new(HashMap::new()));

    let embedded_assets = context.set_assets(Box::new(OTAAssets {
        assets: assets.clone(),
        csp_hashes: Default::default(),
        embedded_assets: Default::default(),
    }));

    let plugin = Builder::<R, Config>::new("ota-updater")
        .invoke_handler(tauri::generate_handler![
            check_for_updates,
            apply_update,
            set_channel
        ])
        .setup(|app, api| {
            let cache_path = app.path().app_cache_dir()?;
            std::fs::create_dir_all(&cache_path)?;

            let current_manifest = std::fs::read_to_string(manifest_path(&cache_path))
                .and_then(|json| {
                    serde_json::from_str::<Manifest>(&json)
                        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
                })
                .unwrap_or_else(|_| Manifest {
                    id: "0".to_string(),
                    archive_signature: "".to_string(),
                    files: HashMap::new(),
                });

            let ota_updater = OTAUpdater {
                cache_path,
                manifest: Arc::new(tauri::async_runtime::Mutex::new(current_manifest)),
                config: Arc::new(tauri::async_runtime::Mutex::new(api.config().clone())),
                assets,
                embedded_assets: Arc::new(Mutex::new(Some(embedded_assets))),
            };

            let _ = tauri::async_runtime::block_on(ota_updater.check_for_updates());

            app.manage(ota_updater);
            Ok(())
        })
        .build();

    (plugin, context)
}

fn base64_to_string(base64_string: &str) -> Result<String> {
    let decoded_string = &base64::engine::general_purpose::STANDARD.decode(base64_string)?;
    let result = std::str::from_utf8(decoded_string)?.to_string();
    Ok(result)
}

async fn load_assets<R: Read>(
    mut archive: Archive<R>,
    manifest: &Manifest,
    public_key: &minisign_verify::PublicKey,
    cache_path: &Path,
) -> Result<HashMap<AssetKey, Vec<u8>>> {
    let mut assets = HashMap::new();

    let archive_out_dir = tempfile::tempdir_in(cache_path)?;
    archive.unpack(archive_out_dir.path())?;
    let dist_dir = archive_out_dir.path().join("dist");

    for entry in walkdir::WalkDir::new(&dist_dir) {
        let entry = entry?;
        let path = entry.path();
        if entry.file_type().is_file() {
            let relative_path = path.strip_prefix(&dist_dir).unwrap();

            let manifest_file =
                manifest
                    .files
                    .get(relative_path)
                    .ok_or(Error::FileNotInManifest {
                        path: relative_path.to_path_buf(),
                    })?;
            let signature_base64_decoded = base64_to_string(&manifest_file.signature)?;
            let signature = minisign_verify::Signature::decode(&signature_base64_decoded)
                .map_err(Error::InvalidSignature)?;

            let data = std::fs::read(path)?;

            public_key
                .verify(&data, &signature, false)
                .map_err(Error::InvalidSignature)?;

            assets.insert(relative_path.into(), data);
        }
    }

    Ok(assets)
}
OSZAR »