zoi-install 1.29.3

Advanced Package Manager & Environment Orchestrator
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
//! Main installer logic.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{Result, anyhow};
use colored::Colorize;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use zoi_core::{cache, config, pgp, pkgdir, recorder, types, utils};
use zoi_db as db;
use zoi_hooks as hooks;
use zoi_resolver::local;

use crate::resolver::InstallNode;
use crate::{manifest, plan, prebuilt, util};

/// Downloads and caches a package archive.
///
/// This function handles:
/// - Checking pkg-dirs and the archive cache.
/// - Downloading from mirrors if not found locally.
/// - Verifying hashes and PGP signatures.
///
/// When `force_redownload` is set, any cached archive, signature, or
/// partial download for this package is discarded and the archive is
/// fetched fresh, skipping the delta-upgrade fast-path as well.
///
/// # Errors
///
/// Returns an error if:
/// - The configuration cannot be read.
/// - The archive cache directory cannot be created.
/// - Zoi is offline and the archive is missing.
/// - The download fails.
/// - Hash verification fails.
/// - Signature verification fails.
pub fn download_and_cache_archive(
    node: &InstallNode,
    details: &plan::PrebuiltDetails,
    pb: Option<&ProgressBar>,
    verbose: bool,
    force_redownload: bool
) -> Result<PathBuf> {
    let config = config::read_config()?;
    let signature_policy =
        config.policy.signature_enforcement.filter(|p| p.enable);

    let archive_cache_root = cache::get_archive_cache_root()?;
    fs::create_dir_all(&archive_cache_root)?;

    // `final_url` comes from registry metadata, so it is untrusted input. The
    // helper only returns a value that is a single inert path component;
    // anything else (empty, or carrying separators/dot segments) falls back to
    // a fixed name rather than being joined onto the cache root.
    let archive_filename = util::get_filename_from_url(&details.info.final_url)
        .unwrap_or("archive.zpa");

    // Defence in depth: assert the invariant the helper promises, so a future
    // change to that helper cannot silently reintroduce a writable path.
    let cached_archive_path =
        utils::safe_join(&archive_cache_root, Path::new(archive_filename))?;
    let sig_filename = format!("{archive_filename}.sig");
    let cached_sig_path =
        utils::safe_join(&archive_cache_root, Path::new(&sig_filename))?;

    let authorities = config
        .default_registry
        .as_ref()
        .filter(|r| r.handle == node.registry_handle)
        .and_then(|r| r.authorities.as_ref())
        .or_else(|| {
            config
                .added_registries
                .iter()
                .find(|r| r.handle == node.registry_handle)
                .and_then(|r| r.authorities.as_ref())
        });
    let has_authorities = authorities.is_some_and(|a| !a.is_empty());
    let pgp_identifiers: Option<Vec<String>> = signature_policy
        .as_ref()
        .map(|p| p.trusted_keys.clone())
        .or_else(|| authorities.cloned());
    let has_pgp_identifiers = pgp_identifiers
        .as_ref()
        .is_some_and(|keys| !keys.is_empty());

    // Track whether the archive was rebuilt from a delta so we can skip
    // the whole-archive checksum (per-pool-entry integrity was already
    // verified during delta application).
    let mut delta_applied = false;

    if force_redownload {
        // Discard anything cached so the archive below is fetched fresh.
        // A stale cached archive is exactly what `--force` must not reuse.
        fs::remove_file(&cached_archive_path).ok();
        fs::remove_file(&cached_sig_path).ok();
        fs::remove_file(
            archive_cache_root.join(format!("{archive_filename}.part"))
        )
        .ok();
        if pb.is_none() {
            println!(
                "Re-downloading archive (--force): {}",
                archive_filename.cyan()
            );
        }
    }

    let archive_path = if let Some(path) =
        pkgdir::find_in_pkg_dirs(archive_filename)
    {
        if pb.is_none() {
            println!("Found archive in pkg-dir: {}", path.display());
        }
        path
    } else if !force_redownload && cached_archive_path.exists() {
        if pb.is_none() {
            println!("Using cached archive: {}", cached_archive_path.display());
        }
        cached_archive_path.clone()
    } else {
        if zoi_core::offline::is_offline() {
            return Err(anyhow!(
                "Archive not found in cache and cannot download: Zoi is in \
                 offline mode. Missing: {archive_filename}"
            ));
        }

        // Delta fast-path: try to fetch and apply `.zdelta` patches
        // sequentially from the cached version up to the target version.
        // Any failure here silently falls back to the full download below.
        // The rebuilt archive is written to `cached_archive_path` so the
        // normal signature checks still run against it. Note: the
        // whole-archive checksum is skipped for delta-rebuilt archives
        // because the tar+zstd byte stream differs from the original while
        // per-pool-entry integrity is already verified during delta
        // application. Skipped entirely on forced re-downloads, which must
        // fetch fresh bytes.
        delta_applied = if force_redownload {
            false
        } else {
            match try_delta_upgrade_sequence(
                node,
                &archive_cache_root,
                &cached_archive_path,
                pb,
                verbose,
                pgp_identifiers.as_deref(),
                config.max_delta_steps
            ) {
                Ok(applied) => applied,
                Err(e) => {
                    if verbose {
                        println!(
                            "{} {e}; falling back to full download.",
                            "Warning:".yellow()
                        );
                    }
                    false
                }
            }
        };

        // If the delta succeeded, `cached_archive_path` now exists and
        // the normal flow will pick it up. Otherwise continue to download.
        if delta_applied {
            cached_archive_path.clone()
        } else {
            let part_path =
                archive_cache_root.join(format!("{archive_filename}.part"));

            if part_path.exists() && pb.is_none() {
                println!("Resuming partial download: {}", part_path.display());
            }

            let mut last_error = None;
            let candidate_urls =
                cache::mirror_candidate_urls(&details.info.final_url);
            let mut downloaded = false;
            for candidate_url in candidate_urls {
                match util::download_file_with_progress(
                    &candidate_url,
                    &part_path,
                    pb,
                    Some(details.download_size)
                ) {
                    Ok(()) => {
                        downloaded = true;
                        break;
                    }
                    Err(e) => last_error = Some((candidate_url, e))
                }
            }
            if !downloaded {
                let (url, error) = last_error.ok_or_else(|| {
                    anyhow!("archive download failed but no error recorded")
                })?;
                return Err(anyhow!(
                    "Failed to download package archive from {url}: {error}"
                ));
            }

            fs::rename(&part_path, &cached_archive_path)?;
            cached_archive_path.clone()
        }
    };

    // Delta-rebuilt archives already passed per-pool-entry structural
    // verification inside `apply_zpa_delta`, and their tar+zstd byte
    // stream will differ from the original, so skip the whole-archive
    // checksum for them.
    if !delta_applied && let Some(hash_url) = &details.info.hash_url {
        let hash = db::get_package_hash_from_db(
            &node.registry_handle,
            &node.pkg.name,
            node.sub_package.as_deref(),
            &node.pkg.repo
        )
        .unwrap_or(None)
        .filter(|hash| !hash.is_empty());
        let hash = match hash {
            Some(hash) => hash,
            None => util::get_expected_hash(hash_url, Some(archive_filename))
                .map_err(|error| {
                    anyhow!(
                        "Unable to obtain the required checksum for '{}': \
                         {error}",
                        node.pkg.name
                    )
                })?
        };

        if !util::verify_file_hash(&archive_path, &hash, pb)? {
            return Err(anyhow!("Hash verification failed"));
        }
    }

    validate_signature_requirements(
        signature_policy.is_some(),
        details.info.pgp_url.is_some(),
        has_pgp_identifiers
    )?;

    // Delta-rebuilt archives skip archive-level signature re-verification,
    // just like the whole-archive hash above. Detached `.sig` sidecars sign
    // the publisher's original bytes, which the rebuilt tar+zstd stream
    // differs from by design, so they can never verify; and already
    // published deltas may carry a stale or missing embedded `manifest.sig`.
    // Trust instead comes from the delta chain itself: the delta patch hash
    // is mandatory, the delta signature is verified whenever trusted keys
    // are configured, the base archive was verified at its install time,
    // and every rebuilt pool entry is hash-verified during application.
    if delta_applied {
        if verbose {
            println!(
                "{}",
                "Skipping archive signature re-verification for delta-rebuilt \
                 archive (delta chain already verified)."
                    .dimmed()
            );
        }
    } else {
        // An embedded `manifest.sig` entry travels inside the archive itself,
        // so it is preferred over a detached sidecar: it works even
        // when the archive is distributed out-of-band without its
        // `.sig`.
        let mut embedded_verified = false;
        if let Some(ref identifiers) = pgp_identifiers
            && !identifiers.is_empty()
            && !matches!(archive_filename.rsplit('.').next(), Some("zsa"))
        {
            let trusted_certs =
                pgp::get_certs_by_name_or_fingerprint(identifiers)?;
            match try_verify_embedded_signature(&archive_path, trusted_certs) {
                Ok(true) => {
                    if verbose {
                        println!(
                            "{}",
                            "Embedded signature verified successfully.".green()
                        );
                    }
                    embedded_verified = true;
                }
                Ok(false) => {}
                Err(e) => {
                    return Err(anyhow!(
                        "Embedded signature verification failed: {e}"
                    ));
                }
            }
        }

        if !embedded_verified
            && let Some(pgp_url) = &details.info.pgp_url
            && let Some(ref identifiers) = pgp_identifiers
            && !identifiers.is_empty()
        {
            let sig_path = if cached_sig_path.exists() {
                cached_sig_path.clone()
            } else {
                if zoi_core::offline::is_offline() {
                    return Err(anyhow!(
                        "Signature not found in cache and cannot download: \
                         Zoi is in offline mode."
                    ));
                }
                let temp_dir =
                    tempfile::Builder::new().prefix("zoi-sig-dl-").tempdir()?;
                let temp_sig_path = temp_dir.path().join(&sig_filename);
                let mut last_error = None;
                let mut downloaded = false;
                for candidate_url in cache::mirror_candidate_urls(pgp_url) {
                    match util::download_file_with_progress(
                        &candidate_url,
                        &temp_sig_path,
                        pb,
                        None
                    ) {
                        Ok(()) => {
                            downloaded = true;
                            break;
                        }
                        Err(e) => last_error = Some((candidate_url, e))
                    }
                }
                if !downloaded {
                    let (url, error) = last_error.ok_or_else(|| {
                        anyhow!(
                            "signature download failed but no error recorded"
                        )
                    })?;
                    return Err(anyhow!(
                        "Failed to download signature from {url}: {error}"
                    ));
                }
                fs::copy(&temp_sig_path, &cached_sig_path)?;
                cached_sig_path.clone()
            };

            if verbose {
                println!("Verifying signature...");
            }
            let trusted_certs =
                pgp::get_certs_by_name_or_fingerprint(identifiers)?;
            pgp::verify_detached_signature_multi_key(
                &archive_path,
                &sig_path,
                trusted_certs
            )?;
            if verbose {
                println!("{}", "Signature verified successfully.".green());
            }
        } else if !embedded_verified
            && details.info.pgp_url.is_none()
            && has_authorities
        {
            let msg = format!(
                "Warning: Installing unsigned package '{}' from a registry \
                 that claims to be secure.",
                node.pkg.name
            );
            if let Some(p) = pb {
                p.println(msg.yellow().to_string());
            } else {
                println!("{}", msg.yellow());
            }
            if signature_policy.is_some() {
                return Err(anyhow!(
                    "Signature enforcement is active, but no PGP URL found \
                     for package"
                ));
            }
        }
    }

    Ok(archive_path)
}

/// Downloads and applies a single `.zdelta` patch upgrading `base_path`
/// (`base_version`) to `to_version`, writing the rebuilt archive into
/// `work_dir`.
///
/// Uses explicit delta URLs from repo.yaml (delta section). The `{version}`
/// placeholder in delta URLs refers to the version being upgraded to.
/// Verifies the delta patch file's hash and signature before applying it.
///
/// # Errors
///
/// Returns an error when no delta is configured, the delta cannot be
/// downloaded, its hash or signature fails verification, or the patch
/// cannot be applied. The caller treats any error as "delta unavailable"
/// and falls back to a full download.
fn fetch_and_apply_delta(
    node: &InstallNode,
    base_path: &Path,
    base_version: &str,
    to_version: &str,
    work_dir: &Path,
    pb: Option<&ProgressBar>,
    verbose: bool,
    pgp_identifiers: Option<&[String]>
) -> Result<PathBuf> {
    // Look up explicit delta info from repo.yaml
    let Some(delta_info) = crate::util::find_delta_info(
        &node.pkg,
        &node.registry_handle,
        base_version,
        to_version
    )?
    else {
        return Err(anyhow!(
            "No delta configuration found for '{}' v{to_version}",
            node.pkg.name
        ));
    };

    if verbose {
        println!(
            "Attempting delta upgrade from v{base_version} to v{to_version}..."
        );
    }

    let delta_path = work_dir.join(format!("upgrade-{to_version}.zdelta"));
    let mut downloaded = false;
    for candidate_url in cache::mirror_candidate_urls(&delta_info.final_url) {
        if util::download_file_with_progress(
            &candidate_url,
            &delta_path,
            pb,
            None
        )
        .is_ok()
        {
            downloaded = true;
            break;
        }
    }
    if !downloaded {
        return Err(anyhow!(
            "No delta available for '{}' v{base_version} -> v{to_version}",
            node.pkg.name
        ));
    }

    // Verify delta patch hash - this is mandatory for integrity.
    let expected_delta_hash =
        delta_info.hash_url.as_ref().ok_or_else(|| {
            anyhow!(
                "Delta configuration missing required hash URL for package \
                 '{}'",
                node.pkg.name
            )
        })?;
    let expected = util::get_expected_hash(expected_delta_hash, None)?;
    if !util::verify_file_hash(&delta_path, &expected, pb)? {
        return Err(anyhow!(
            "Delta hash verification failed for '{}' v{to_version}",
            node.pkg.name
        ));
    }

    // Verify delta patch signature if PGP URL and trusted keys available.
    if let Some(pgp_url) = &delta_info.pgp_url
        && let Some(identifiers) = pgp_identifiers
        && !identifiers.is_empty()
    {
        let temp_sig_path = work_dir.join(format!("upgrade-{to_version}.sig"));
        let mut downloaded = false;
        for candidate_url in cache::mirror_candidate_urls(pgp_url) {
            if util::download_file_with_progress(
                &candidate_url,
                &temp_sig_path,
                pb,
                None
            )
            .is_ok()
            {
                downloaded = true;
                break;
            }
        }
        if downloaded {
            let trusted_certs =
                pgp::get_certs_by_name_or_fingerprint(identifiers)?;
            pgp::verify_detached_signature_multi_key(
                &delta_path,
                &temp_sig_path,
                trusted_certs
            )?;
            if verbose {
                println!(
                    "{}",
                    "Delta signature verified successfully.".green()
                );
            }
        } else if verbose {
            println!(
                "{} Delta signature file not found; skipping signature \
                 verification.",
                "Warning:".yellow()
            );
        }
    } else if verbose {
        println!(
            "{} No trusted PGP keys for delta signature verification.",
            "Warning:".yellow()
        );
    }

    let rebuilt_path = work_dir.join(format!("rebuilt-{to_version}.zpa"));
    zoi_package::delta::apply_zpa_delta(base_path, &delta_path, &rebuilt_path)?;
    if verbose {
        println!("{}", "Delta applied successfully.".green());
    }
    Ok(rebuilt_path)
}

/// Attempts to upgrade a package archive via a sequence of `.zdelta` patches
/// from a cached older version up to the target version.
///
/// When the cached version is more than one release behind the target (e.g.
/// cached `149`, target `151`), each intermediate delta is tried in order:
/// `149 -> 150`, then `150 -> 151`, rebuilding the archive step by step on
/// top of the previously rebuilt output. Intermediate versions are read
/// from the package database. The number of steps is limited by
/// `max_delta_steps` from the user config (default `3`, since Zoidberg only
/// keeps the last three versions as `.zpa`/`.zsa` and `.zdelta`); anything
/// beyond that falls back to a full download.
///
/// Returns `Ok(false)` whenever a delta is unavailable or cannot be applied
/// so the caller can fall back to a full download.
fn try_delta_upgrade_sequence(
    node: &InstallNode,
    archive_cache_root: &Path,
    target_path: &Path,
    pb: Option<&ProgressBar>,
    verbose: bool,
    pgp_identifiers: Option<&[String]>,
    max_delta_steps: u32
) -> Result<bool> {
    let Ok(target_version) = semver::Version::parse(&node.version) else {
        return Ok(false);
    };

    // Find the newest cached archive of the same package on the same
    // platform that is older than the target version. Archive names follow
    // `{name}-{version}-{platform}.zpa`.
    let platform = zoi_core::utils::get_platform().unwrap_or_default();
    let prefix = format!("{}-", node.pkg.name);
    let suffix = format!("-{platform}.zpa");
    let mut best: Option<(semver::Version, PathBuf)> = None;
    let entries = std::fs::read_dir(archive_cache_root).ok();
    let Some(entries) = entries else {
        return Ok(false);
    };
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if !name.starts_with(&prefix) || !name.ends_with(&suffix) {
            continue;
        }
        let middle = &name[prefix.len()..name.len() - suffix.len()];
        let version_str = middle.trim_start_matches('v');
        let Ok(version) = semver::Version::parse(version_str) else {
            continue;
        };
        if version >= target_version {
            continue;
        }
        if best.as_ref().is_none_or(|(v, _)| version > *v) {
            best = Some((version, entry.path()));
        }
    }
    let Some((base_version, base_path)) = best else {
        return Ok(false);
    };

    // Determine the intermediate versions between the cached base and the
    // target from the package database, e.g. base `149` and target `151`
    // give steps [`150`, `151`].
    let mut steps: Vec<(semver::Version, String)> = Vec::new();
    if let Ok(db_versions) = db::get_all_versions(
        &node.registry_handle,
        &node.pkg.name,
        &node.pkg.repo
    ) {
        for version_string in db_versions {
            let parsed =
                semver::Version::parse(&version_string).or_else(|_| {
                    semver::Version::parse(
                        version_string.trim_start_matches('v')
                    )
                });
            let Ok(version) = parsed else {
                continue;
            };
            if version > base_version && version <= target_version {
                steps.push((version, version_string));
            }
        }
        steps.sort_by(|a, b| a.0.cmp(&b.0));
        steps.dedup_by(|a, b| a.0 == b.0);
    }
    // If the database knows nothing about the versions in between, fall
    // back to a single direct delta attempt from the base to the target.
    if steps.is_empty() {
        steps.push((target_version.clone(), node.version.clone()));
    }

    if steps.len() as u32 > max_delta_steps {
        if verbose {
            println!(
                "{} Upgrade spans {} versions but at most {max_delta_steps} \
                 delta steps are configured; falling back to full download.",
                "Warning:".yellow(),
                steps.len()
            );
        }
        return Ok(false);
    }

    let work_dir = tempfile::Builder::new()
        .prefix("zoi-delta-")
        .tempdir_in(archive_cache_root)?;
    let mut current_base = base_path;
    let mut current_version = base_version.to_string();
    for (_, step_string) in &steps {
        match fetch_and_apply_delta(
            node,
            &current_base,
            &current_version,
            step_string,
            work_dir.path(),
            pb,
            verbose,
            pgp_identifiers
        ) {
            Ok(rebuilt) => {
                current_base = rebuilt;
                current_version.clone_from(step_string);
            }
            Err(e) => {
                if verbose {
                    println!(
                        "{} {e}; falling back to full download.",
                        "Warning:".yellow()
                    );
                }
                return Ok(false);
            }
        }
    }

    // Every delta step verified and applied successfully. The rebuilt archive
    // is trusted because:
    // - The base archive was already verified (full hash + sig on install)
    // - Each delta patch was verified (hash + optionally sig)
    // - Each delta application does per-pool-entry structural verification
    // We skip the whole-archive hash check since the tar+zstd stream differs
    // from the original but the content is verified.
    //
    // The work dir lives inside `archive_cache_root` so this persist stays on
    // the same filesystem. The copy fallback inside the helper covers
    // exotic mounts; otherwise a cross-device error would be swallowed by
    // the caller's delta fallback and surface as a confusing full `.zpa`
    // re-download after "Delta applied successfully."
    persist_rebuilt_archive(&current_base, target_path)?;
    if verbose {
        println!("{}", "All delta steps applied successfully.".green());
    }
    Ok(true)
}

/// Persists a delta-rebuilt archive to its final cache location.
///
/// Uses an atomic rename when possible, falling back to copy + remove for
/// robustness (e.g. exotic mounts where the staging dir and the cache live
/// on different filesystems). Without the fallback, a cross-device rename
/// error would be swallowed by the caller's delta fallback and surface as
/// a confusing full `.zpa` re-download after "Delta applied successfully."
fn persist_rebuilt_archive(src: &Path, dst: &Path) -> Result<()> {
    if fs::rename(src, dst).is_err() {
        fs::copy(src, dst)?;
        fs::remove_file(src).ok();
    }
    Ok(())
}

/// Attempts to verify an embedded `manifest.sig` entry inside a downloaded
/// archive against the pooled `manifest.json` it signs.
///
/// Returns `Ok(false)` when the archive carries no embedded signature pair,
/// letting the caller fall back to the detached sidecar flow.
///
/// # Errors
///
/// Returns an error if the archive cannot be read or the signature does not
/// verify.
fn try_verify_embedded_signature(
    archive_path: &Path,
    trusted_certs: Vec<pgp::sequoia_openpgp::Cert>
) -> Result<bool> {
    use std::io::Read;

    let file = fs::File::open(archive_path)?;
    let decoder = zstd::stream::read::Decoder::new(file)?;
    let mut archive = tar::Archive::new(decoder);

    let mut manifest_bytes: Option<Vec<u8>> = None;
    let mut sig_bytes: Option<Vec<u8>> = None;
    for entry in archive.entries()? {
        let mut entry = entry?;
        let name = entry.path()?.to_string_lossy().to_string();
        match Path::new(&name).file_name().and_then(|f| f.to_str()) {
            Some("manifest.json") if manifest_bytes.is_none() => {
                let mut buf = Vec::new();
                entry.read_to_end(&mut buf)?;
                manifest_bytes = Some(buf);
            }
            Some("manifest.sig") => {
                let mut buf = Vec::new();
                entry.read_to_end(&mut buf)?;
                sig_bytes = Some(buf);
            }
            _ => {}
        }
    }

    let (Some(manifest), Some(sig)) = (manifest_bytes, sig_bytes) else {
        return Ok(false);
    };

    // Reuse the existing path-based multi-key verifier on temporary files so
    // we sign-verify the exact bytes that ship inside the archive.
    let temp_dir = tempfile::Builder::new()
        .prefix("zoi-embed-sig-")
        .tempdir()?;
    let manifest_path = temp_dir.path().join("manifest.json");
    let sig_path = temp_dir.path().join("manifest.sig");
    fs::write(&manifest_path, &manifest)?;
    fs::write(&sig_path, &sig)?;
    pgp::verify_detached_signature_multi_key(
        &manifest_path,
        &sig_path,
        trusted_certs
    )?;
    Ok(true)
}

/// Ensures that an enforced signature policy has everything needed to verify
/// the downloaded archive before it is installed.
fn validate_signature_requirements(
    enforcement_enabled: bool,
    has_signature_url: bool,
    has_trusted_keys: bool
) -> Result<()> {
    if !enforcement_enabled {
        return Ok(());
    }
    if !has_signature_url {
        return Err(anyhow!(
            "Signature enforcement is active, but no PGP URL was found for \
             the package"
        ));
    }
    if !has_trusted_keys {
        return Err(anyhow!(
            "Signature enforcement is active, but no trusted PGP keys are \
             configured"
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{persist_rebuilt_archive, validate_signature_requirements};

    #[test]
    fn signature_enforcement_requires_a_signature_url() {
        assert!(validate_signature_requirements(true, false, true).is_err());
    }

    #[test]
    fn signature_enforcement_requires_trusted_keys() {
        assert!(validate_signature_requirements(true, true, false).is_err());
    }

    #[test]
    fn disabled_signature_enforcement_allows_missing_metadata() {
        assert!(validate_signature_requirements(false, false, false).is_ok());
    }

    #[test]
    fn persist_rebuilt_archive_moves_content_to_target() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = dir.path().join("rebuilt-1.6.3.zpa");
        let dst = dir.path().join("zbsdiff-1.6.3-linux-amd64.zpa");
        std::fs::write(&src, b"rebuilt-archive-bytes").expect("write src");
        persist_rebuilt_archive(&src, &dst).expect("persist");
        assert!(!src.exists(), "source should be moved away");
        assert_eq!(
            std::fs::read(&dst).expect("read dst"),
            b"rebuilt-archive-bytes"
        );
    }

    #[test]
    fn persist_rebuilt_archive_overwrites_stale_target() {
        let dir = tempfile::tempdir().expect("tempdir");
        let src = dir.path().join("rebuilt-1.6.3.zpa");
        let dst = dir.path().join("zbsdiff-1.6.3-linux-amd64.zpa");
        std::fs::write(&src, b"new-bytes").expect("write src");
        std::fs::write(&dst, b"stale-bytes").expect("write dst");
        persist_rebuilt_archive(&src, &dst).expect("persist");
        assert_eq!(std::fs::read(&dst).expect("read dst"), b"new-bytes");
    }
}

/// Information about a package that has been prepared for installation.
#[derive(Clone)]
pub struct PreparedNode {
    /// Path to the downloaded or built archive.
    pub archive_path: PathBuf,
    /// The method used for installation (e.g. "pre-compiled", "source").
    pub install_method: String,
    /// Whether the archive was built from source.
    pub is_build: bool
}

/// Performs the non-destructive first phase of installation: "Preparation".
///
/// Preparation includes:
/// - Downloading pre-built archives from the registry.
/// - Verifying checksums and PGP signatures (Root of Trust).
/// - Or, building the package from source in a temporary sandbox if requested.
///
/// This phase always runs in user-space and does not modify the system state
/// or the package store.
///
/// When `force_redownload` is set, cached archives are discarded and
/// fetched fresh instead of being reused.
///
/// # Errors
///
/// Returns an error if:
/// - The archive cannot be downloaded or built.
/// - The progress bar style cannot be created.
pub fn prepare_node(
    node: &InstallNode,
    action: &plan::InstallAction,
    m: Option<&MultiProgress>,
    build_type: Option<&str>,
    verbose: bool,
    force_redownload: bool
) -> Result<PreparedNode> {
    let pkg = &node.pkg;
    let version = &node.version;

    let pb_style = ProgressStyle::default_bar()
        .template(
            "{spinner:.green} {msg:30.cyan} [{bar:40.cyan/blue}] {percent}%"
        )?
        .progress_chars("#>-");

    let spinner_style = ProgressStyle::default_spinner()
        .template("{spinner:.green} {msg:30.cyan}")?
        .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ");

    let display_name = if let Some(sub) = &node.sub_package {
        format!("{}:{}", pkg.name, sub)
    } else {
        pkg.name.clone()
    };
    let version_display = if node.revision == "1" {
        version.clone()
    } else {
        format!("{}-{}", version, node.revision)
    };
    let message = format!("zoi:{display_name}@{version_display}");

    let pb = if let Some(m_inner) = m {
        let pb = m_inner.add(ProgressBar::new(100));
        pb.set_style(pb_style);
        pb.set_message(message.clone());
        Some(pb)
    } else {
        None
    };

    let (archive_path, install_method, is_build) = match action {
        plan::InstallAction::DownloadAndInstall(details) => {
            if let Some(p) = &pb {
                p.set_message("Downloading package...");
            }
            let archive_path = download_and_cache_archive(
                node,
                details,
                pb.as_ref(),
                verbose,
                force_redownload
            )?;
            (archive_path, "pre-compiled".to_string(), false)
        }
        plan::InstallAction::InstallFromArchive(archive_path) => {
            if archive_path.to_string_lossy().ends_with(".zsa") {
                if let Some(p) = &pb {
                    p.set_style(spinner_style);
                    p.enable_steady_tick(std::time::Duration::from_millis(100));
                    p.set_message(format!("Building {display_name}..."));
                }
                let archive_path = prebuilt::build_archive(
                    archive_path,
                    pkg,
                    node.sub_package.as_deref(),
                    build_type,
                    pb.as_ref(),
                    !verbose
                )?;
                match archive_path {
                    Some(path) => (path, "source".to_string(), true),
                    None => (PathBuf::new(), "meta".to_string(), false)
                }
            } else {
                if let Some(p) = &pb {
                    p.set_message("Using local archive...");
                    p.finish();
                }
                (archive_path.clone(), "pre-compiled".to_string(), false)
            }
        }
        plan::InstallAction::BuildAndInstall => {
            if let Some(p) = &pb {
                p.set_style(spinner_style);
                p.enable_steady_tick(std::time::Duration::from_millis(100));
                p.set_message(format!("Building {display_name}..."));
            }
            let pkg_lua_path = Path::new(&node.source);
            let archive_path = prebuilt::build_archive(
                pkg_lua_path,
                pkg,
                node.sub_package.as_deref(),
                build_type,
                pb.as_ref(),
                !verbose
            )?;

            match archive_path {
                Some(path) => (path, "source".to_string(), true),
                None => (PathBuf::new(), "meta".to_string(), false)
            }
        }
    };

    if let Some(p) = pb {
        p.finish_and_clear();
    }

    Ok(PreparedNode {
        archive_path,
        install_method,
        is_build
    })
}

/// Performs the destructive second phase of installation: "Execution".
///
/// This phase takes a `PreparedNode` and:
/// - Unpacks the archive into the versioned store directory.
/// - Creates binary shims in the global Zoi `bin` directory.
/// - Registers the installation in the registry database and lockfile.
///
/// Just-in-Time Escalation: If the target scope is `system`, this function
/// will spawn a privileged sub-process (`sudo zoi helper elevate-install-node`)
/// to perform the final file moves, keeping the main CLI unprivileged.
///
/// # Errors
///
/// Returns an error if:
/// - Hooks fail to run.
/// - Privilege escalation fails.
/// - The archive cannot be unpacked.
/// - The manifest cannot be created or written.
/// - The package cannot be recorded in the database.
pub fn install_prepared_node(
    node: &InstallNode,
    prepared: &PreparedNode,
    m: Option<&MultiProgress>,
    yes: bool,
    record: bool,
    link_bins: bool,
    _verbose: bool
) -> Result<types::InstallManifest> {
    let pkg = &node.pkg;
    let version = &node.version;
    let handle = &node.registry_handle;
    let is_direct = matches!(node.reason, types::InstallReason::Direct);

    let pb_style = ProgressStyle::default_spinner()
        .template("{spinner:.green} {msg:30.cyan}")?
        .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ");

    let main_pb = if let Some(m_inner) = m {
        if is_direct {
            None
        } else {
            let pb = m_inner.add(ProgressBar::new_spinner());
            pb.set_style(pb_style.clone());
            let name = if let Some(sub) = &node.sub_package {
                format!("{}:{}", pkg.name, sub)
            } else {
                pkg.name.clone()
            };
            let version_display = if node.revision == "1" {
                version.clone()
            } else {
                format!("{}-{}", version, node.revision)
            };
            pb.set_message(format!("zoi:{name}@{version_display}"));
            pb.enable_steady_tick(std::time::Duration::from_millis(100));
            Some(pb)
        }
    } else {
        None
    };

    let step_pb = if is_direct && let Some(m_inner) = m {
        let pb = m_inner.add(ProgressBar::new_spinner());
        pb.set_style(pb_style);
        pb.enable_steady_tick(std::time::Duration::from_millis(100));
        Some(pb)
    } else {
        None
    };

    if let Some(hooks) = &pkg.hooks {
        if let Some(pb) = &step_pb {
            pb.set_message("Running pre-install hooks...");
        }
        hooks::run_hooks(hooks, hooks::HookType::PreInstall, pkg.scope)?;
    }

    let sub_package_to_install = node.sub_package.clone();
    let sub_packages_vec = sub_package_to_install.clone().map(|s| vec![s]);

    let archive_path = &prepared.archive_path;
    let install_method = &prepared.install_method;

    let needs_escalation =
        pkg.scope == types::Scope::System && !zoi_core::utils::is_admin();

    let install_manifest = if needs_escalation {
        let escalator =
            zoi_core::utils::get_privilege_escalator().ok_or_else(|| {
                anyhow!(
                    "Root privileges required for system scope installation, \
                     but neither 'sudo' nor 'doas' was found."
                )
            })?;

        if let Some(pb) = step_pb.as_ref().or(main_pb.as_ref()) {
            pb.set_message(format!(
                "Waiting for {escalator} privileges to install system \
                 package..."
            ));
        }

        let node_json = serde_json::to_string(node)?;
        let mut temp_file = tempfile::NamedTempFile::new()?;
        temp_file.write_all(node_json.as_bytes())?;
        let temp_path = temp_file.path();

        let mut cmd = std::process::Command::new(escalator);
        cmd.arg(std::env::current_exe()?);
        cmd.arg("helper").arg("elevate-install-node");
        cmd.arg("--node-json").arg(temp_path);
        cmd.arg("--archive").arg(archive_path);
        cmd.arg("--install-method").arg(install_method);
        if yes {
            cmd.arg("--yes");
        }
        if link_bins {
            cmd.arg("--link-bins");
        }

        let status = cmd
            .status()
            .map_err(|e| anyhow!("Failed to spawn privilege escalator: {e}"))?;
        if !status.success() {
            return Err(anyhow!("Escalated installation failed."));
        }

        let version_dir = local::get_package_version_dir(
            pkg.scope,
            &node.registry_handle,
            &pkg.repo,
            &pkg.name,
            &node.version
        )?;
        let manifest_path = local::find_store_manifest(
            &version_dir,
            node.sub_package.as_deref()
        )
        .ok_or_else(|| {
            anyhow!(
                "Escalated install did not leave a manifest in '{}'",
                version_dir.display()
            )
        })?;
        local::read_store_manifest(&manifest_path)?
    } else {
        if let Some(pb) = step_pb.as_ref().or(main_pb.as_ref()) {
            pb.set_message(format!("Installing {}...", pkg.name.cyan()));
        }

        let (installed_files, file_digests) = crate::pkg_install::run(
            archive_path,
            Some(pkg.scope),
            &node.registry_handle,
            Some(&node.version),
            yes,
            sub_packages_vec,
            link_bins,
            step_pb.as_ref().or(main_pb.as_ref())
        )?;

        if let types::InstallReason::Dependency { ref parent } = node.reason {
            let package_dir = local::get_package_dir(
                pkg.scope, handle, &pkg.repo, &pkg.name
            )?;
            local::add_dependent(&package_dir, parent)?;
        }

        let install_manifest = manifest::create_manifest(
            pkg,
            node.reason.clone(),
            node.dependencies.clone(),
            Some(install_method.clone()),
            installed_files,
            handle,
            node.repo_type.clone(),
            &node.chosen_options,
            &node.chosen_optionals,
            sub_package_to_install.clone(),
            file_digests
        )?;

        if record {
            local::write_manifest(&install_manifest)?;
            local::persist_package_source(
                &install_manifest,
                Path::new(&node.source)
            )?;
        }

        install_manifest
    };

    if prepared.is_build {
        let _ = fs::remove_file(archive_path);
    }

    if record {
        if let Ok(conn) = db::open_connection("local")
            && let Ok(pkg_id) = db::update_package(
                &conn,
                pkg,
                handle,
                Some(pkg.scope),
                sub_package_to_install.as_deref(),
                Some(&node.reason)
            )
        {
            let _ = db::clear_package_files(&conn, pkg_id);
            let _ = db::index_package_files(
                &conn,
                pkg_id,
                &install_manifest.installed_files
            );
        }

        if let Err(e) = recorder::record_package(
            pkg,
            &node.reason,
            &node.dependencies,
            handle,
            &node.repo_type,
            &node.chosen_options,
            &node.chosen_optionals,
            sub_package_to_install.as_deref(),
            &node.source,
            node.git_sha.as_deref()
        ) {
            eprintln!(
                "Warning: failed to record package installation for '{}': {}",
                pkg.name, e
            );
        }
    }

    if let Some(hooks) = &pkg.hooks {
        if let Some(pb) = &step_pb {
            pb.set_message("Running post-install hooks...");
        }
        hooks::run_hooks(hooks, hooks::HookType::PostInstall, pkg.scope)?;
    }

    if let Some(pb) = main_pb {
        pb.finish();
    }
    if let Some(pb) = step_pb {
        pb.finish();
    }

    util::send_telemetry("install", pkg, handle, Some(install_method));

    Ok(install_manifest)
}

/// Performs both preparation and execution phases for an install node.
///
/// When `force_redownload` is set, cached archives are discarded and
/// fetched fresh instead of being reused.
///
/// # Errors
///
/// Returns an error if preparation or execution fails.
pub fn install_node(
    node: &InstallNode,
    action: &plan::InstallAction,
    m: Option<&MultiProgress>,
    build_type: Option<&str>,
    yes: bool,
    record: bool,
    link_bins: bool,
    verbose: bool,
    force_redownload: bool
) -> Result<types::InstallManifest> {
    let prepared =
        prepare_node(node, action, m, build_type, verbose, force_redownload)?;
    install_prepared_node(node, &prepared, m, yes, record, link_bins, verbose)
}