kael 0.2.0

GPU-accelerated native UI framework for Rust — build desktop apps with Metal, DirectX, and Vulkan rendering
Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
//! Cross-platform auto-updater module.
//!
//! Provides an API for checking a configurable URL for available updates,
//! downloading update packages in the background with progress callbacks,
//! and applying updates with application restart.
//!
//! Supports Sparkle appcast XML and a simpler JSON feed format for update
//! discovery.

use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context as _, Result, anyhow, bail};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use ed25519_dalek::{Signature, VerifyingKey};
use futures::AsyncReadExt as _;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};

use kael_release::update::{UpdateChannel, UpdateManifest, verify_manifest};
use semantic_version::SemanticVersion;

/// Configuration for the auto-updater.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoUpdaterConfig {
    /// URL of the update feed (appcast XML or JSON).
    pub feed_url: String,
    /// How often to check for updates.
    #[serde(with = "duration_secs")]
    pub check_interval: Duration,
    /// Whether to include pre-release versions.
    pub allow_prerelease: bool,
}

/// Information about an available update.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateInfo {
    /// The version of the available update.
    pub version: SemanticVersion,
    /// Optional release notes (HTML or plain text).
    pub release_notes: Option<String>,
    /// URL to download the update package.
    pub download_url: String,
    /// Base64-encoded ed25519 signature over the release manifest.
    pub signature: Option<String>,
    /// Expected SHA-256 (lowercase hex) of the downloaded package.
    #[serde(default)]
    pub sha256: Option<String>,
    /// Expected size of the downloaded package in bytes.
    #[serde(default)]
    pub size_bytes: Option<u64>,
}

/// Progress information during an update download.
#[derive(Debug, Clone, Copy)]
pub struct DownloadProgress {
    /// Bytes downloaded so far.
    pub bytes_downloaded: u64,
    /// Total bytes to download, if known.
    pub total_bytes: Option<u64>,
}

impl DownloadProgress {
    /// Returns the download progress as a fraction in `[0.0, 1.0]`, or `None`
    /// if the total size is unknown.
    pub fn fraction(&self) -> Option<f64> {
        self.total_bytes
            .map(|total| self.bytes_downloaded as f64 / total as f64)
    }
}

/// The current state of the auto-updater.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UpdateStatus {
    /// No update activity.
    Idle,
    /// Checking the feed for updates.
    Checking,
    /// An update is available.
    UpdateAvailable(SemanticVersion),
    /// Downloading the update package.
    Downloading,
    /// The update has been downloaded and is ready to install.
    ReadyToInstall,
    /// An error occurred.
    Error(String),
}

/// Trait for platform-specific update installation.
///
/// Each platform provides its own implementation:
/// - macOS: Sparkle-compatible `.dmg`/`.zip` handling
/// - Windows: MSI/NSIS `.exe` installer execution
/// - Linux: AppImage delta updates or Flatpak/Snap update channels
pub trait PlatformInstaller: Send + Sync {
    /// Install the update from the downloaded package at `path` and restart
    /// the application.
    fn install_and_restart(&self, package_path: &std::path::Path) -> Result<()>;
}

/// The auto-updater.
///
/// Checks a configurable URL for available updates, downloads update packages
/// in the background, and delegates installation to a [`PlatformInstaller`].
pub struct AutoUpdater {
    config: AutoUpdaterConfig,
    current_version: SemanticVersion,
    http_client: Arc<dyn http_client::HttpClient>,
    installer: Option<Arc<dyn PlatformInstaller>>,
    status: UpdateStatus,
    latest_update: Option<UpdateInfo>,
    downloaded_path: Option<std::path::PathBuf>,
    verifying_key: Option<VerifyingKey>,
    update_channel: UpdateChannel,
    require_signature: bool,
}

impl AutoUpdater {
    /// Create a new auto-updater with the given configuration and current
    /// application version.
    pub fn new(
        config: AutoUpdaterConfig,
        current_version: SemanticVersion,
        http_client: Arc<dyn http_client::HttpClient>,
    ) -> Self {
        Self {
            config,
            current_version,
            http_client,
            installer: None,
            status: UpdateStatus::Idle,
            latest_update: None,
            downloaded_path: None,
            verifying_key: None,
            update_channel: UpdateChannel::Stable,
            require_signature: true,
        }
    }

    /// Set the platform-specific installer backend.
    pub fn set_installer(&mut self, installer: Arc<dyn PlatformInstaller>) {
        self.installer = Some(installer);
    }

    /// Configure the ed25519 public key used to authenticate update manifests.
    ///
    /// `public_key` must be the 32-byte ed25519 public key whose private
    /// counterpart signs release manifests. Once configured, every downloaded
    /// package is refused before installation unless it carries a valid
    /// signature over a manifest matching its advertised version, channel, URL,
    /// hash, and size, and the downloaded bytes hash to that signed SHA-256.
    pub fn set_public_key(&mut self, public_key: &[u8]) -> Result<()> {
        let key_array: [u8; 32] = public_key
            .try_into()
            .map_err(|_| anyhow!("ed25519 public key must be exactly 32 bytes"))?;
        let key = VerifyingKey::from_bytes(&key_array)
            .map_err(|_| anyhow!("invalid ed25519 public key"))?;
        self.verifying_key = Some(key);
        Ok(())
    }

    /// Configure the ed25519 public key from a hex-encoded string.
    pub fn set_public_key_hex(&mut self, hex_key: &str) -> Result<()> {
        let bytes = hex::decode(hex_key.trim()).context("update public key is not valid hex")?;
        self.set_public_key(&bytes)
    }

    /// Set the release channel whose manifests this updater trusts.
    ///
    /// The channel participates in the signed manifest payload, so it must match
    /// the channel the publisher signed for. Defaults to the stable channel.
    pub fn set_update_channel(&mut self, channel: impl AsRef<str>) {
        self.update_channel = channel_from_str(channel.as_ref());
    }

    /// Control whether a valid signature and hash are mandatory before install.
    ///
    /// Defaults to `true` (fail closed). Disabling this re-opens the updater to
    /// installing unverified packages and is intended only for tests or
    /// environments that guarantee package integrity by other means.
    pub fn set_require_signature(&mut self, require: bool) {
        self.require_signature = require;
    }

    /// Returns the current update status.
    pub fn status(&self) -> &UpdateStatus {
        &self.status
    }

    /// Returns the latest update info, if an update was found.
    pub fn latest_update(&self) -> Option<&UpdateInfo> {
        self.latest_update.as_ref()
    }

    /// Returns the auto-updater configuration.
    pub fn config(&self) -> &AutoUpdaterConfig {
        &self.config
    }

    /// Check the configured feed URL for available updates.
    ///
    /// Returns `Some(UpdateInfo)` if a newer version is available, `None`
    /// otherwise.
    pub async fn check_for_updates(&mut self) -> Result<Option<UpdateInfo>> {
        self.status = UpdateStatus::Checking;

        let mut response = self
            .http_client
            .get(&self.config.feed_url, Default::default(), false)
            .await
            .context("failed to fetch update feed")?;

        let status = response.status();
        if !status.is_success() {
            let msg = format!("update feed returned HTTP {}", status.as_u16());
            self.status = UpdateStatus::Error(msg.clone());
            bail!("{}", msg);
        }

        let mut body = Vec::new();
        response
            .body_mut()
            .read_to_end(&mut body)
            .await
            .context("failed to read update feed body")?;

        let body_str = String::from_utf8_lossy(&body);

        let updates = parse_update_feed(&body_str)?;

        let latest = updates
            .into_iter()
            // SemanticVersion currently does not preserve pre-release metadata,
            // so feed filtering is limited to version ordering for now.
            .filter(|u| u.version > self.current_version)
            .max_by_key(|u| u.version);

        if let Some(ref update) = latest {
            self.status = UpdateStatus::UpdateAvailable(update.version);
            self.latest_update = Some(update.clone());
        } else {
            self.status = UpdateStatus::Idle;
            self.latest_update = None;
        }

        Ok(latest)
    }

    /// Download the latest available update in the background.
    ///
    /// Calls `on_progress` periodically with download progress information.
    /// Returns the path to the downloaded package on success.
    pub async fn download_update(
        &mut self,
        on_progress: impl Fn(DownloadProgress) + Send + 'static,
    ) -> Result<std::path::PathBuf> {
        let update = self
            .latest_update
            .as_ref()
            .ok_or_else(|| anyhow!("no update available to download"))?
            .clone();

        self.status = UpdateStatus::Downloading;

        let mut response = self
            .http_client
            .get(&update.download_url, Default::default(), false)
            .await
            .context("failed to start update download")?;

        let status = response.status();
        if !status.is_success() {
            let msg = format!("update download returned HTTP {}", status.as_u16());
            self.status = UpdateStatus::Error(msg.clone());
            bail!("{}", msg);
        }

        let total_bytes = response
            .headers()
            .get("content-length")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u64>().ok());

        let mut bytes = Vec::new();
        response
            .body_mut()
            .read_to_end(&mut bytes)
            .await
            .context("failed to read update package")?;

        on_progress(DownloadProgress {
            bytes_downloaded: bytes.len() as u64,
            total_bytes,
        });

        if let Err(err) = self.verify_package(&update, &bytes) {
            self.downloaded_path = None;
            self.status = UpdateStatus::Error(err.to_string());
            return Err(err).context("update package failed verification; refusing to install");
        }

        let staging_dir =
            std::env::temp_dir().join(format!("kael_update_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&staging_dir)
            .context("failed to create update staging directory")?;
        restrict_dir_permissions(&staging_dir);

        let download_path = staging_dir.join(sanitize_package_filename(&update.download_url));
        std::fs::write(&download_path, &bytes).context("failed to write update package to disk")?;

        self.downloaded_path = Some(download_path.clone());
        self.status = UpdateStatus::ReadyToInstall;

        Ok(download_path)
    }

    fn verify_package(&self, update: &UpdateInfo, bytes: &[u8]) -> Result<()> {
        match self.verifying_key.as_ref() {
            Some(key) => {
                let signature_b64 = update.signature.as_deref().ok_or_else(|| {
                    anyhow!("update is unsigned but signature verification is required")
                })?;
                let signature_bytes = BASE64
                    .decode(signature_b64)
                    .context("update signature is not valid base64")?;
                let signature_array: [u8; 64] = signature_bytes
                    .as_slice()
                    .try_into()
                    .map_err(|_| anyhow!("update signature must be 64 bytes"))?;
                let signature = Signature::from_bytes(&signature_array);

                let sha256 = update
                    .sha256
                    .as_deref()
                    .ok_or_else(|| anyhow!("signed update is missing its sha256 hash"))?;
                let size_bytes = update
                    .size_bytes
                    .ok_or_else(|| anyhow!("signed update is missing its size"))?;

                let manifest = UpdateManifest {
                    version: update.version.to_string(),
                    channel: self.update_channel.clone(),
                    url: update.download_url.clone(),
                    sha256: sha256.to_string(),
                    size_bytes,
                    release_notes: None,
                    min_version: None,
                };
                if !verify_manifest(&manifest, &signature, key) {
                    bail!("update signature verification failed");
                }
            }
            None => {
                if self.require_signature {
                    bail!(
                        "auto-update signature verification is required but no public key is configured"
                    );
                }
            }
        }

        match update.sha256.as_deref() {
            Some(expected) => {
                if let Some(expected_size) = update.size_bytes {
                    if bytes.len() as u64 != expected_size {
                        bail!(
                            "update size mismatch: expected {expected_size} bytes, downloaded {}",
                            bytes.len()
                        );
                    }
                }
                let actual = sha256_hex(bytes);
                if actual.len() != expected.len() || !actual.eq_ignore_ascii_case(expected) {
                    bail!("update hash mismatch: expected {expected}, downloaded {actual}");
                }
            }
            None => {
                if self.require_signature {
                    bail!("update is missing a sha256 hash; cannot verify integrity");
                }
            }
        }

        Ok(())
    }

    /// Install the downloaded update and restart the application.
    ///
    /// Requires a [`PlatformInstaller`] to be set via [`set_installer`].
    ///
    /// [`set_installer`]: Self::set_installer
    pub fn install_and_restart(&self) -> Result<()> {
        let installer = self
            .installer
            .as_ref()
            .ok_or_else(|| anyhow!("no platform installer configured"))?;

        let path = self
            .downloaded_path
            .as_ref()
            .ok_or_else(|| anyhow!("no update has been downloaded"))?;

        installer.install_and_restart(path)
    }
}

fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex::encode(hasher.finalize())
}

fn channel_from_str(channel: &str) -> UpdateChannel {
    let trimmed = channel.trim();
    if trimmed.eq_ignore_ascii_case("stable") {
        UpdateChannel::Stable
    } else if trimmed.eq_ignore_ascii_case("beta") {
        UpdateChannel::Beta
    } else if trimmed.eq_ignore_ascii_case("nightly") {
        UpdateChannel::Nightly
    } else {
        UpdateChannel::Custom(trimmed.to_string())
    }
}

fn sanitize_package_filename(download_url: &str) -> String {
    let candidate = download_url
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or("")
        .split(['?', '#'])
        .next()
        .unwrap_or("");
    let cleaned: String = candidate
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
        .collect();
    if cleaned.is_empty() || cleaned == "." || cleaned == ".." {
        "update_package".to_string()
    } else {
        cleaned
    }
}

fn restrict_dir_permissions(dir: &std::path::Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
    }
    #[cfg(not(unix))]
    {
        let _ = dir;
    }
}

// ---------------------------------------------------------------------------
// Update feed parsing
// ---------------------------------------------------------------------------

/// Parse an update feed, auto-detecting Sparkle appcast XML vs JSON format.
pub fn parse_update_feed(body: &str) -> Result<Vec<UpdateInfo>> {
    let trimmed = body.trim();
    if trimmed.starts_with('<') {
        parse_appcast_xml(trimmed)
    } else if trimmed.starts_with('[') || trimmed.starts_with('{') {
        parse_json_feed(trimmed)
    } else {
        bail!("unrecognized update feed format");
    }
}

/// A single item from a JSON update feed.
#[derive(Debug, Deserialize)]
struct JsonFeedItem {
    version: String,
    #[serde(default)]
    release_notes: Option<String>,
    download_url: String,
    #[serde(default)]
    signature: Option<String>,
    #[serde(default)]
    sha256: Option<String>,
    #[serde(default)]
    size_bytes: Option<u64>,
}

/// Parse a JSON update feed.
///
/// Accepts either a JSON array of items or a single object with an `"items"`
/// array.
fn parse_json_feed(body: &str) -> Result<Vec<UpdateInfo>> {
    // Try array-of-items first
    let items: Vec<JsonFeedItem> = if body.trim().starts_with('[') {
        serde_json::from_str(body).context("failed to parse JSON update feed as array")?
    } else {
        #[derive(Deserialize)]
        struct Wrapper {
            items: Vec<JsonFeedItem>,
        }
        let wrapper: Wrapper =
            serde_json::from_str(body).context("failed to parse JSON update feed as object")?;
        wrapper.items
    };

    items
        .into_iter()
        .map(|item| {
            let version = item
                .version
                .parse::<SemanticVersion>()
                .context(format!("invalid version string: {}", item.version))?;
            Ok(UpdateInfo {
                version,
                release_notes: item.release_notes,
                download_url: item.download_url,
                signature: item.signature,
                sha256: item.sha256,
                size_bytes: item.size_bytes,
            })
        })
        .collect()
}

/// Parse a Sparkle appcast XML feed.
///
/// Extracts `<item>` elements and reads `<enclosure>` attributes for download
/// URL, version, and signature. Release notes come from `<description>`.
fn parse_appcast_xml(body: &str) -> Result<Vec<UpdateInfo>> {
    let mut updates = Vec::new();

    // Simple streaming XML parser — we don't pull in a full XML crate.
    // Sparkle appcast structure:
    //   <rss><channel>
    //     <item>
    //       <title>...</title>
    //       <description>...</description>
    //       <enclosure url="..." sparkle:version="..." sparkle:dsaSignature="..." />
    //     </item>
    //   </channel></rss>

    for item_block in split_xml_items(body) {
        let version_str = extract_xml_attr(&item_block, "sparkle:version")
            .or_else(|| extract_xml_attr(&item_block, "sparkle:shortVersionString"))
            .or_else(|| extract_xml_tag_content(&item_block, "sparkle:version"));

        let download_url = extract_xml_attr(&item_block, "url");

        let signature = extract_xml_attr(&item_block, "sparkle:edSignature")
            .or_else(|| extract_xml_attr(&item_block, "sparkle:dsaSignature"));

        let sha256 = extract_xml_attr(&item_block, "sparkle:sha256")
            .or_else(|| extract_xml_attr(&item_block, "sha256"));

        let size_bytes =
            extract_xml_attr(&item_block, "length").and_then(|len| len.parse::<u64>().ok());

        let release_notes = extract_xml_tag_content(&item_block, "description");

        if let (Some(version_str), Some(download_url)) = (version_str, download_url) {
            if let Ok(version) = version_str.parse::<SemanticVersion>() {
                updates.push(UpdateInfo {
                    version,
                    release_notes,
                    download_url,
                    signature,
                    sha256,
                    size_bytes,
                });
            }
        }
    }

    Ok(updates)
}

/// Split XML body into `<item>...</item>` blocks.
fn split_xml_items(body: &str) -> Vec<String> {
    let mut items = Vec::new();
    let lower = body.to_lowercase();
    let mut search_from = 0;

    while let Some(pos) = lower[search_from..]
        .find("<item>")
        .or_else(|| lower[search_from..].find("<item "))
    {
        let start = search_from + pos;
        let end = match lower[start..].find("</item>") {
            Some(pos) => start + pos + "</item>".len(),
            None => break,
        };
        items.push(body[start..end].to_string());
        search_from = end;
    }

    items
}

/// Extract the value of an XML attribute by name from a block of XML text.
fn extract_xml_attr(block: &str, attr_name: &str) -> Option<String> {
    let search = format!("{}=\"", attr_name);
    let start = block.find(&search)?;
    let value_start = start + search.len();
    let value_end = block[value_start..].find('"')? + value_start;
    Some(block[value_start..value_end].to_string())
}

/// Extract the text content of an XML tag by name.
fn extract_xml_tag_content(block: &str, tag_name: &str) -> Option<String> {
    let open = format!("<{}", tag_name);
    let close = format!("</{}>", tag_name);

    let start = block.find(&open)?;
    let after_open = block[start..].find('>')? + start + 1;
    let end = block[after_open..].find(&close)? + after_open;

    let content = block[after_open..end].trim().to_string();
    if content.is_empty() {
        None
    } else {
        Some(content)
    }
}

// ---------------------------------------------------------------------------
// Platform-specific installer backends
// ---------------------------------------------------------------------------

/// macOS installer: handles Sparkle-compatible `.dmg` and `.zip` packages.
///
/// For `.zip` packages the archive is extracted to a temporary directory and
/// the contained `.app` bundle is moved over the running application before
/// restarting.
///
/// For `.dmg` packages the disk image is attached via `hdiutil`, the `.app`
/// bundle is copied from the mounted volume, and the image is detached.
#[cfg(target_os = "macos")]
pub struct MacInstaller;

#[cfg(target_os = "macos")]
impl PlatformInstaller for MacInstaller {
    fn install_and_restart(&self, package_path: &std::path::Path) -> Result<()> {
        let ext = package_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");

        let app_bundle = resolve_running_app_bundle()?;

        match ext {
            "zip" => {
                let temp_dir = std::env::temp_dir().join("gpui_update_extract");
                if temp_dir.exists() {
                    std::fs::remove_dir_all(&temp_dir)?;
                }
                std::fs::create_dir_all(&temp_dir)?;

                let status = std::process::Command::new("ditto")
                    .args([
                        "-xk",
                        &package_path.to_string_lossy(),
                        &temp_dir.to_string_lossy(),
                    ])
                    .status()
                    .context("failed to run ditto to extract zip")?;

                if !status.success() {
                    bail!("ditto extraction failed with status {}", status);
                }

                let new_app = find_app_bundle_in(&temp_dir)?;
                replace_app_bundle(&new_app, &app_bundle)?;
            }
            "dmg" => {
                let mount_point = std::env::temp_dir().join("gpui_update_dmg");
                if mount_point.exists() {
                    // Try to detach any previous mount
                    let _ = std::process::Command::new("hdiutil")
                        .args(["detach", &mount_point.to_string_lossy(), "-quiet"])
                        .status();
                    let _ = std::fs::remove_dir_all(&mount_point);
                }
                std::fs::create_dir_all(&mount_point)?;

                let status = std::process::Command::new("hdiutil")
                    .args([
                        "attach",
                        &package_path.to_string_lossy(),
                        "-mountpoint",
                        &mount_point.to_string_lossy(),
                        "-nobrowse",
                        "-quiet",
                    ])
                    .status()
                    .context("failed to run hdiutil attach")?;

                if !status.success() {
                    bail!("hdiutil attach failed with status {}", status);
                }

                let result = (|| -> Result<()> {
                    let new_app = find_app_bundle_in(&mount_point)?;
                    replace_app_bundle(&new_app, &app_bundle)
                })();

                // Always detach
                let _ = std::process::Command::new("hdiutil")
                    .args(["detach", &mount_point.to_string_lossy(), "-quiet"])
                    .status();

                result?;
            }
            other => bail!("unsupported macOS package format: .{}", other),
        }

        // Restart the application
        let status = std::process::Command::new("open")
            .args(["-n", &app_bundle.to_string_lossy()])
            .status()
            .context("failed to restart application")?;

        if !status.success() {
            bail!("failed to restart application, open returned {}", status);
        }

        std::process::exit(0);
    }
}

/// Resolve the path to the currently running `.app` bundle on macOS.
#[cfg(target_os = "macos")]
fn resolve_running_app_bundle() -> Result<std::path::PathBuf> {
    let exe = std::env::current_exe().context("failed to get current executable path")?;
    // Typical layout: Foo.app/Contents/MacOS/foo
    let app_bundle = exe
        .parent() // MacOS/
        .and_then(|p| p.parent()) // Contents/
        .and_then(|p| p.parent()) // Foo.app/
        .ok_or_else(|| anyhow!("could not determine .app bundle path from executable"))?;
    Ok(app_bundle.to_path_buf())
}

/// Find the first `.app` bundle inside a directory.
#[cfg(target_os = "macos")]
fn find_app_bundle_in(dir: &std::path::Path) -> Result<std::path::PathBuf> {
    for entry in std::fs::read_dir(dir).context("failed to read extraction directory")? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) == Some("app") {
            return Ok(path);
        }
    }
    bail!("no .app bundle found in {}", dir.display())
}

/// Replace the existing app bundle with the new one.
#[cfg(target_os = "macos")]
fn replace_app_bundle(new_app: &std::path::Path, existing_app: &std::path::Path) -> Result<()> {
    let backup = existing_app.with_extension("app.bak");
    if backup.exists() {
        std::fs::remove_dir_all(&backup)?;
    }
    std::fs::rename(existing_app, &backup)
        .context("failed to move existing app bundle to backup")?;

    let status = std::process::Command::new("cp")
        .args([
            "-R",
            &new_app.to_string_lossy(),
            &existing_app.to_string_lossy(),
        ])
        .status()
        .context("failed to copy new app bundle")?;

    if !status.success() {
        // Attempt to restore backup
        let _ = std::fs::rename(&backup, existing_app);
        bail!("failed to copy new app bundle into place");
    }

    let _ = std::fs::remove_dir_all(&backup);
    Ok(())
}

/// Windows installer: executes MSI or NSIS `.exe` installer packages.
///
/// For `.msi` packages, `msiexec /i` is used with quiet mode and restart.
/// For `.exe` packages (NSIS), the installer is executed with `/S` (silent)
/// flag.
#[cfg(target_os = "windows")]
pub struct WindowsInstaller;

#[cfg(target_os = "windows")]
impl PlatformInstaller for WindowsInstaller {
    fn install_and_restart(&self, package_path: &std::path::Path) -> Result<()> {
        let ext = package_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");

        match ext {
            "msi" => {
                // Use msiexec to install the MSI package silently and restart
                let status = std::process::Command::new("msiexec")
                    .args([
                        "/i",
                        &package_path.to_string_lossy(),
                        "/quiet",
                        "/norestart",
                    ])
                    .status()
                    .context("failed to run msiexec")?;

                if !status.success() {
                    bail!("msiexec failed with status {}", status);
                }
            }
            "exe" => {
                // Execute NSIS installer in silent mode
                let status = std::process::Command::new(package_path)
                    .args(["/S"])
                    .status()
                    .context("failed to run NSIS installer")?;

                if !status.success() {
                    bail!("NSIS installer failed with status {}", status);
                }
            }
            other => bail!("unsupported Windows package format: .{}", other),
        }

        // Restart: re-launch the current executable
        let exe = std::env::current_exe().context("failed to get current executable path")?;
        let _ = std::process::Command::new(exe)
            .spawn()
            .context("failed to restart application")?;

        std::process::exit(0);
    }
}

/// Linux installer: handles AppImage delta updates, Flatpak, and Snap update
/// channels.
///
/// - For AppImage packages (`.AppImage`), the new image replaces the running
///   one and is made executable.
/// - For Flatpak apps, `flatpak update` is invoked.
/// - For Snap apps, `snap refresh` is invoked.
/// - Generic packages are treated as AppImage replacements.
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub struct LinuxInstaller {
    /// The packaging format hint. When `None`, the installer infers the
    /// format from the package file extension or the running environment.
    pub format_hint: Option<LinuxPackageFormat>,
}

/// Supported Linux packaging formats for auto-update.
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinuxPackageFormat {
    /// AppImage — replace the running image file.
    AppImage,
    /// Flatpak — delegate to `flatpak update`.
    Flatpak,
    /// Snap — delegate to `snap refresh`.
    Snap,
}

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
impl LinuxInstaller {
    /// Create a new Linux installer with automatic format detection.
    pub fn new() -> Self {
        Self { format_hint: None }
    }

    /// Create a new Linux installer with an explicit format hint.
    pub fn with_format(format: LinuxPackageFormat) -> Self {
        Self {
            format_hint: Some(format),
        }
    }

    /// Detect the packaging format from the environment or package path.
    fn detect_format(&self, package_path: &std::path::Path) -> LinuxPackageFormat {
        if let Some(hint) = self.format_hint {
            return hint;
        }

        // Check file extension
        let ext = package_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");

        if ext.eq_ignore_ascii_case("appimage") {
            return LinuxPackageFormat::AppImage;
        }

        // Check environment for Flatpak
        if std::env::var("FLATPAK_ID").is_ok() {
            return LinuxPackageFormat::Flatpak;
        }

        // Check environment for Snap
        if std::env::var("SNAP").is_ok() {
            return LinuxPackageFormat::Snap;
        }

        // Default to AppImage replacement
        LinuxPackageFormat::AppImage
    }
}

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
impl PlatformInstaller for LinuxInstaller {
    fn install_and_restart(&self, package_path: &std::path::Path) -> Result<()> {
        let format = self.detect_format(package_path);

        match format {
            LinuxPackageFormat::AppImage => {
                let exe =
                    std::env::current_exe().context("failed to get current executable path")?;

                // Replace the running AppImage with the new one
                let backup = exe.with_extension("bak");
                if backup.exists() {
                    std::fs::remove_file(&backup)?;
                }
                std::fs::rename(&exe, &backup)
                    .context("failed to move current AppImage to backup")?;

                if let Err(e) = std::fs::copy(package_path, &exe) {
                    // Attempt to restore backup
                    let _ = std::fs::rename(&backup, &exe);
                    return Err(e).context("failed to copy new AppImage into place");
                }

                // Make executable
                let status = std::process::Command::new("chmod")
                    .args(["+x", &exe.to_string_lossy()])
                    .status()
                    .context("failed to chmod new AppImage")?;

                if !status.success() {
                    let _ = std::fs::rename(&backup, &exe);
                    bail!("chmod failed with status {}", status);
                }

                let _ = std::fs::remove_file(&backup);

                // Restart
                let _ = std::process::Command::new(&exe)
                    .spawn()
                    .context("failed to restart AppImage")?;

                std::process::exit(0);
            }
            LinuxPackageFormat::Flatpak => {
                let app_id =
                    std::env::var("FLATPAK_ID").unwrap_or_else(|_| "current-app".to_string());

                let status = std::process::Command::new("flatpak")
                    .args(["update", "-y", &app_id])
                    .status()
                    .context("failed to run flatpak update")?;

                if !status.success() {
                    bail!("flatpak update failed with status {}", status);
                }

                // Restart via flatpak run
                let _ = std::process::Command::new("flatpak")
                    .args(["run", &app_id])
                    .spawn()
                    .context("failed to restart Flatpak application")?;

                std::process::exit(0);
            }
            LinuxPackageFormat::Snap => {
                let snap_name =
                    std::env::var("SNAP_NAME").unwrap_or_else(|_| "current-app".to_string());

                let status = std::process::Command::new("snap")
                    .args(["refresh", &snap_name])
                    .status()
                    .context("failed to run snap refresh")?;

                if !status.success() {
                    bail!("snap refresh failed with status {}", status);
                }

                // Restart via snap run
                let _ = std::process::Command::new("snap")
                    .args(["run", &snap_name])
                    .spawn()
                    .context("failed to restart Snap application")?;

                std::process::exit(0);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Serde helper for Duration as seconds
// ---------------------------------------------------------------------------

mod duration_secs {
    use serde::{Deserialize, Deserializer, Serializer};
    use std::time::Duration;

    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(duration.as_secs())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        let secs = u64::deserialize(deserializer)?;
        Ok(Duration::from_secs(secs))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_json_feed_array() {
        let json = r#"[
            {
                "version": "1.2.3",
                "release_notes": "Bug fixes",
                "download_url": "https://example.com/update-1.2.3.zip",
                "signature": "abc123"
            },
            {
                "version": "1.1.0",
                "download_url": "https://example.com/update-1.1.0.zip"
            }
        ]"#;

        let updates = parse_update_feed(json).unwrap();
        assert_eq!(updates.len(), 2);
        assert_eq!(updates[0].version, SemanticVersion::new(1, 2, 3));
        assert_eq!(updates[0].release_notes.as_deref(), Some("Bug fixes"));
        assert_eq!(
            updates[0].download_url,
            "https://example.com/update-1.2.3.zip"
        );
        assert_eq!(updates[0].signature.as_deref(), Some("abc123"));
        assert_eq!(updates[1].version, SemanticVersion::new(1, 1, 0));
        assert!(updates[1].release_notes.is_none());
        assert!(updates[1].signature.is_none());
    }

    #[test]
    fn test_parse_json_feed_object_wrapper() {
        let json = r#"{
            "items": [
                {
                    "version": "2.0.0",
                    "download_url": "https://example.com/v2.zip"
                }
            ]
        }"#;

        let updates = parse_update_feed(json).unwrap();
        assert_eq!(updates.len(), 1);
        assert_eq!(updates[0].version, SemanticVersion::new(2, 0, 0));
    }

    #[test]
    fn test_parse_appcast_xml() {
        let xml = r#"<?xml version="1.0" encoding="utf-8"?>
        <rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
            <channel>
                <title>My App Updates</title>
                <item>
                    <title>Version 3.1.0</title>
                    <description>New features and improvements</description>
                    <enclosure url="https://example.com/MyApp-3.1.0.dmg"
                               sparkle:version="3.1.0"
                               sparkle:dsaSignature="sig123"
                               length="12345678"
                               type="application/octet-stream" />
                </item>
                <item>
                    <title>Version 3.0.0</title>
                    <enclosure url="https://example.com/MyApp-3.0.0.dmg"
                               sparkle:version="3.0.0"
                               length="11111111"
                               type="application/octet-stream" />
                </item>
            </channel>
        </rss>"#;

        let updates = parse_update_feed(xml).unwrap();
        assert_eq!(updates.len(), 2);
        assert_eq!(updates[0].version, SemanticVersion::new(3, 1, 0));
        assert_eq!(
            updates[0].download_url,
            "https://example.com/MyApp-3.1.0.dmg"
        );
        assert_eq!(updates[0].signature.as_deref(), Some("sig123"));
        assert_eq!(
            updates[0].release_notes.as_deref(),
            Some("New features and improvements")
        );
        assert_eq!(updates[1].version, SemanticVersion::new(3, 0, 0));
        assert!(updates[1].signature.is_none());
    }

    #[test]
    fn test_parse_appcast_xml_with_ed_signature() {
        let xml = r#"<rss><channel>
            <item>
                <enclosure url="https://example.com/app.zip"
                           sparkle:version="1.0.0"
                           sparkle:edSignature="ed_sig_value" />
            </item>
        </channel></rss>"#;

        let updates = parse_update_feed(xml).unwrap();
        assert_eq!(updates.len(), 1);
        assert_eq!(updates[0].signature.as_deref(), Some("ed_sig_value"));
    }

    #[test]
    fn test_parse_empty_json_array() {
        let updates = parse_update_feed("[]").unwrap();
        assert!(updates.is_empty());
    }

    #[test]
    fn test_parse_unrecognized_format() {
        let result = parse_update_feed("this is not valid");
        assert!(result.is_err());
    }

    #[test]
    fn test_download_progress_fraction() {
        let progress = DownloadProgress {
            bytes_downloaded: 50,
            total_bytes: Some(100),
        };
        assert_eq!(progress.fraction(), Some(0.5));

        let unknown = DownloadProgress {
            bytes_downloaded: 50,
            total_bytes: None,
        };
        assert_eq!(unknown.fraction(), None);
    }

    #[test]
    fn test_config_serialization_roundtrip() {
        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/appcast.xml".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: AutoUpdaterConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.feed_url, config.feed_url);
        assert_eq!(deserialized.check_interval, config.check_interval);
        assert_eq!(deserialized.allow_prerelease, config.allow_prerelease);
    }

    #[test]
    fn test_update_info_serialization_roundtrip() {
        let info = UpdateInfo {
            version: SemanticVersion::new(2, 5, 1),
            release_notes: Some("Fixed a bug".to_string()),
            download_url: "https://example.com/v2.5.1.zip".to_string(),
            signature: Some("sig_value".to_string()),
            sha256: Some("a".repeat(64)),
            size_bytes: Some(4096),
        };

        let json = serde_json::to_string(&info).unwrap();
        let deserialized: UpdateInfo = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.version, info.version);
        assert_eq!(deserialized.release_notes, info.release_notes);
        assert_eq!(deserialized.download_url, info.download_url);
        assert_eq!(deserialized.signature, info.signature);
        assert_eq!(deserialized.sha256, info.sha256);
        assert_eq!(deserialized.size_bytes, info.size_bytes);
    }

    #[test]
    fn test_auto_updater_initial_state() {
        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/feed".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };
        let client = http_client::FakeHttpClient::with_200_response();
        let updater = AutoUpdater::new(config, SemanticVersion::new(1, 0, 0), client);

        assert_eq!(*updater.status(), UpdateStatus::Idle);
        assert!(updater.latest_update().is_none());
    }

    #[test]
    fn test_install_without_installer_errors() {
        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/feed".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };
        let client = http_client::FakeHttpClient::with_200_response();
        let updater = AutoUpdater::new(config, SemanticVersion::new(1, 0, 0), client);

        let result = updater.install_and_restart();
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // Update verification tests (RCE hotfix)
    // -----------------------------------------------------------------------

    fn signed_update_fixture(bytes: &[u8], channel: UpdateChannel) -> (VerifyingKey, UpdateInfo) {
        use ed25519_dalek::SigningKey;

        let signing_key = SigningKey::from_bytes(&[7u8; 32]);
        let verifying_key = signing_key.verifying_key();

        let sha256 = sha256_hex(bytes);
        let size_bytes = bytes.len() as u64;
        let version = SemanticVersion::new(1, 2, 0);
        let download_url = "https://example.com/MyApp-1.2.0.zip".to_string();

        let manifest = UpdateManifest {
            version: version.to_string(),
            channel,
            url: download_url.clone(),
            sha256: sha256.clone(),
            size_bytes,
            release_notes: None,
            min_version: None,
        };
        let signature = kael_release::update::sign_manifest(&manifest, &signing_key);
        let signature_b64 = BASE64.encode(signature.to_bytes());

        (
            verifying_key,
            UpdateInfo {
                version,
                release_notes: None,
                download_url,
                signature: Some(signature_b64),
                sha256: Some(sha256),
                size_bytes: Some(size_bytes),
            },
        )
    }

    fn updater_with_key(key: &VerifyingKey) -> AutoUpdater {
        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/feed".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };
        let client = http_client::FakeHttpClient::with_200_response();
        let mut updater = AutoUpdater::new(config, SemanticVersion::new(1, 0, 0), client);
        updater.set_public_key(key.as_bytes()).unwrap();
        updater
    }

    #[test]
    fn test_verify_package_accepts_genuine_payload() {
        let bytes = b"genuine update payload".to_vec();
        let (key, update) = signed_update_fixture(&bytes, UpdateChannel::Stable);
        let updater = updater_with_key(&key);
        assert!(updater.verify_package(&update, &bytes).is_ok());
    }

    #[test]
    fn test_verify_package_rejects_tampered_bytes() {
        let bytes = b"genuine update payload".to_vec();
        let (key, update) = signed_update_fixture(&bytes, UpdateChannel::Stable);
        let updater = updater_with_key(&key);

        let tampered = b"malware payload xxxxxx".to_vec();
        assert_eq!(tampered.len(), bytes.len());
        let err = updater.verify_package(&update, &tampered).unwrap_err();
        assert!(err.to_string().contains("hash mismatch"), "{err}");
    }

    #[test]
    fn test_verify_package_rejects_unsigned_when_key_configured() {
        let bytes = b"genuine update payload".to_vec();
        let (key, mut update) = signed_update_fixture(&bytes, UpdateChannel::Stable);
        update.signature = None;
        let updater = updater_with_key(&key);
        let err = updater.verify_package(&update, &bytes).unwrap_err();
        assert!(err.to_string().contains("unsigned"), "{err}");
    }

    #[test]
    fn test_verify_package_rejects_wrong_key() {
        let bytes = b"genuine update payload".to_vec();
        let (_real_key, update) = signed_update_fixture(&bytes, UpdateChannel::Stable);
        let other = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]).verifying_key();
        let updater = updater_with_key(&other);
        let err = updater.verify_package(&update, &bytes).unwrap_err();
        assert!(
            err.to_string().contains("signature verification failed"),
            "{err}"
        );
    }

    #[test]
    fn test_verify_package_rejects_channel_mismatch() {
        let bytes = b"genuine update payload".to_vec();
        let (key, update) = signed_update_fixture(&bytes, UpdateChannel::Beta);
        let mut updater = updater_with_key(&key);
        updater.set_update_channel("stable");
        assert!(updater.verify_package(&update, &bytes).is_err());
    }

    #[test]
    fn test_verify_fails_closed_without_public_key() {
        let bytes = b"genuine update payload".to_vec();
        let (_key, update) = signed_update_fixture(&bytes, UpdateChannel::Stable);
        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/feed".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };
        let client = http_client::FakeHttpClient::with_200_response();
        let updater = AutoUpdater::new(config, SemanticVersion::new(1, 0, 0), client);
        let err = updater.verify_package(&update, &bytes).unwrap_err();
        assert!(
            err.to_string().contains("no public key is configured"),
            "{err}"
        );
    }

    #[test]
    fn test_sanitize_package_filename_stays_a_single_path_component() {
        use std::path::{Component, Path};

        let adversarial = [
            "https://example.com/releases/kael-1.2.3.dmg",
            "https://example.com/kael.dmg?token=secret#frag",
            "https://example.com/../../etc/passwd",
            "https://example.com/foo/..",
            "https://example.com/a\\b\\evil.exe",
            "https://example.com/",
            "https://example.com/???",
            "file:///etc/shadow",
            "../../../../root/.ssh/authorized_keys",
            "",
            ".",
            "..",
            "/absolute/evil",
        ];

        for url in adversarial {
            let name = sanitize_package_filename(url);
            assert!(!name.is_empty(), "empty name for {url:?}");
            assert!(
                !name.contains('/') && !name.contains('\\'),
                "separator survived for {url:?}: {name:?}"
            );
            assert_ne!(name, "..", "traversal token survived for {url:?}");

            let components: Vec<_> = Path::new(&name).components().collect();
            assert_eq!(
                components.len(),
                1,
                "{url:?} -> {name:?} is not exactly one path component"
            );
            assert!(
                matches!(components[0], Component::Normal(_)),
                "{url:?} -> {name:?} is not a normal path component"
            );
        }
    }

    #[test]
    fn test_download_update_rejects_tampered_before_ready() {
        use http_client::{AsyncBody, FakeHttpClient, Response};

        let genuine = b"genuine update payload".to_vec();
        let (key, update) = signed_update_fixture(&genuine, UpdateChannel::Stable);

        let served = b"malware payload xxxxxx".to_vec();
        let client = FakeHttpClient::create(move |_req| {
            let body = served.clone();
            async move {
                Ok(Response::builder()
                    .status(200)
                    .body(AsyncBody::from(body))
                    .unwrap())
            }
        });

        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/feed".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };
        let mut updater = AutoUpdater::new(config, SemanticVersion::new(1, 0, 0), client);
        updater.set_public_key(key.as_bytes()).unwrap();
        updater.latest_update = Some(update);

        let result = smol::block_on(updater.download_update(|_| {}));
        assert!(result.is_err());
        assert!(matches!(updater.status(), UpdateStatus::Error(_)));
        assert_ne!(*updater.status(), UpdateStatus::ReadyToInstall);
        assert!(updater.downloaded_path.is_none());
        assert!(updater.install_and_restart().is_err());
    }

    #[test]
    fn test_download_update_accepts_genuine_and_marks_ready() {
        use http_client::{AsyncBody, FakeHttpClient, Response};

        let genuine = b"genuine update payload".to_vec();
        let (key, update) = signed_update_fixture(&genuine, UpdateChannel::Stable);

        let served = genuine.clone();
        let client = FakeHttpClient::create(move |_req| {
            let body = served.clone();
            async move {
                Ok(Response::builder()
                    .status(200)
                    .body(AsyncBody::from(body))
                    .unwrap())
            }
        });

        let config = AutoUpdaterConfig {
            feed_url: "https://example.com/feed".to_string(),
            check_interval: Duration::from_secs(3600),
            allow_prerelease: false,
        };
        let mut updater = AutoUpdater::new(config, SemanticVersion::new(1, 0, 0), client);
        updater.set_public_key(key.as_bytes()).unwrap();
        updater.latest_update = Some(update);

        let path = smol::block_on(updater.download_update(|_| {})).unwrap();
        assert_eq!(*updater.status(), UpdateStatus::ReadyToInstall);
        assert!(path.exists());

        let path_str = path.to_string_lossy();
        assert!(path_str.contains("kael_update_"), "{path_str}");
        assert!(!path_str.contains("gpui_update_"), "{path_str}");

        let on_disk = std::fs::read(&path).unwrap();
        assert_eq!(on_disk, genuine);

        if let Some(dir) = path.parent() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    // -----------------------------------------------------------------------
    // Platform installer tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_platform_installer_trait_is_object_safe() {
        // Verify PlatformInstaller can be used as a trait object
        fn _assert_object_safe(_: &dyn PlatformInstaller) {}
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_mac_installer_rejects_unsupported_format() {
        let installer = MacInstaller;
        let path = std::path::Path::new("/tmp/update.tar.gz");
        let result = installer.install_and_restart(path);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("unsupported macOS package format")
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_windows_installer_rejects_unsupported_format() {
        let installer = WindowsInstaller;
        let path = std::path::Path::new("C:\\temp\\update.tar.gz");
        let result = installer.install_and_restart(path);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("unsupported Windows package format")
        );
    }

    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    #[test]
    fn test_linux_installer_default_format_detection() {
        let installer = LinuxInstaller::new();
        let appimage_path = std::path::Path::new("/tmp/MyApp.AppImage");
        assert_eq!(
            installer.detect_format(appimage_path),
            LinuxPackageFormat::AppImage
        );
    }

    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    #[test]
    fn test_linux_installer_explicit_format_hint() {
        let installer = LinuxInstaller::with_format(LinuxPackageFormat::Flatpak);
        // Even with an AppImage extension, the hint should take precedence
        let path = std::path::Path::new("/tmp/MyApp.AppImage");
        assert_eq!(installer.detect_format(path), LinuxPackageFormat::Flatpak);
    }

    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    #[test]
    fn test_linux_installer_unknown_extension_defaults_to_appimage() {
        let installer = LinuxInstaller::new();
        let path = std::path::Path::new("/tmp/update.bin");
        // Without FLATPAK_ID or SNAP env vars, should default to AppImage
        assert_eq!(installer.detect_format(path), LinuxPackageFormat::AppImage);
    }

    #[test]
    fn test_appcast_skips_invalid_versions() {
        let xml = r#"<rss><channel>
            <item>
                <enclosure url="https://example.com/app.zip"
                           sparkle:version="not-a-version" />
            </item>
            <item>
                <enclosure url="https://example.com/app2.zip"
                           sparkle:version="1.0.0" />
            </item>
        </channel></rss>"#;

        let updates = parse_update_feed(xml).unwrap();
        assert_eq!(updates.len(), 1);
        assert_eq!(updates[0].version, SemanticVersion::new(1, 0, 0));
    }
}