nexo-ext-installer 0.1.2

Phase 31.1 — fetch + resolve + download + sha256-verify nexo plugin tarballs against the ext-registry index. Building block for `nexo plugin install <id>` (CLI integration in 31.1.c).
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
//! Decentralized GitHub Releases install — building block for
//! `nexo plugin install <owner>/<repo>@<tag>`.
//!
//! Architecture: there is NO central catalog. Each plugin
//! author publishes their plugin as a GitHub Release on their
//! own repo, following the asset naming convention documented
//! in `nexo-plugin-contract.md`. The install CLI hits the
//! GitHub Releases API directly to resolve a coords string into
//! a verified tarball.
//!
//! What this crate does:
//! 1. Parse `<owner>/<repo>@<tag>` coords
//! 2. Fetch the GitHub release JSON (or `/releases/latest`)
//! 3. Parse the release into an [`nexo_ext_registry::ExtEntry`]
//!    using the asset naming convention
//! 4. Download the tarball matching the daemon's target
//! 5. Stream-verify the sha256 (read from the `.sha256` asset)
//!
//! Cosign signature verification lives in [`verify`], tarball
//! extraction in [`extract`]; the CLI wires them together.
//!
//! # References
//!
//! - Internal: `crates/ext-registry/` — entry types.
//! - GitHub Releases API:
//!   `https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name`
//! - Real-world: `cargo binstall` + `gh extension install` —
//!   per-repo binary install via GitHub Releases.

#![deny(missing_docs)]

use std::path::{Path, PathBuf};

use futures::StreamExt;
use nexo_ext_registry::ExtEntry;
use sha2::{Digest, Sha256};
use tokio::io::AsyncWriteExt;

pub mod error;
pub mod extract;
pub mod extract_contract;
pub mod extract_error;
pub mod trusted_keys;
pub mod verify;
pub mod verify_error;

pub use error::InstallError;
pub use extract::{
    extract_verified_tarball, ExtractInput, ExtractLimits, ExtractedPlugin, MAX_ENTRIES,
    MAX_ENTRY_BYTES, MAX_EXTRACTED_BYTES, MAX_TARBALL_BYTES,
};
pub use extract_contract::{ExtractContract, PluginExtractContract};
pub use extract_error::ExtractError;
pub use trusted_keys::{AuthorPolicy, TrustMode, TrustedKeysConfig};
pub use verify::{discover_cosign_binary, verify_plugin_signature, VerifiedSignature, VerifyInput};
pub use verify_error::VerifyError;

/// Parsed `<owner>/<repo>@<tag>` coordinates. `tag` defaults to
/// `latest` when the user omits it.
///
/// Renamed from `PluginCoords` once the same struct started
/// serving non-plugin artifacts (persona packs). The legacy name
/// is kept as a deprecated type alias below for backward compatibility.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoCoords {
    /// GitHub repo owner (user or org).
    pub owner: String,
    /// GitHub repo name.
    pub repo: String,
    /// Release tag (e.g. `v0.2.0`) or the literal `"latest"`
    /// to resolve to GitHub's `/releases/latest` endpoint.
    pub tag: String,
}

/// Legacy alias preserved so existing callers
/// (`src/plugin_install.rs`, `src/plugin_admin.rs`) keep
/// compiling while downstream migrations land. Prefer
/// [`RepoCoords`] in new code.
#[deprecated(
    since = "0.2.0",
    note = "renamed to `RepoCoords`; the same coords serve plugins and personas now"
)]
pub type PluginCoords = RepoCoords;

impl RepoCoords {
    /// Parse `<owner>/<repo>` or `<owner>/<repo>@<tag>`. Tag
    /// defaults to `"latest"` when `@<tag>` is absent.
    pub fn parse(s: &str) -> Result<Self, InstallError> {
        let (coords, tag) = match s.split_once('@') {
            Some((c, t)) => (c, t.to_string()),
            None => (s, "latest".to_string()),
        };
        let (owner, repo) = coords
            .split_once('/')
            .ok_or_else(|| InstallError::CoordsInvalid {
                got: s.to_string(),
                reason: "expected <owner>/<repo>[@<tag>]",
            })?;
        if owner.is_empty() || repo.is_empty() || tag.is_empty() {
            return Err(InstallError::CoordsInvalid {
                got: s.to_string(),
                reason: "owner / repo / tag must not be empty",
            });
        }
        // GitHub allows alphanumerics + `-` + `_` + `.` in
        // owner/repo names. We don't replicate the full GitHub
        // validator; reject the obviously bad chars (whitespace,
        // url-meaningful chars) so a typo fails loud.
        for ch in owner.chars().chain(repo.chars()) {
            if !(ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.') {
                return Err(InstallError::CoordsInvalid {
                    got: s.to_string(),
                    reason: "owner/repo may only contain [A-Za-z0-9._-]",
                });
            }
        }
        Ok(Self {
            owner: owner.to_string(),
            repo: repo.to_string(),
            tag,
        })
    }

    /// GitHub Releases API URL for this coords. When tag is
    /// `"latest"`, hits `/releases/latest`; otherwise hits
    /// `/releases/tags/<tag>`. The base URL is configurable for
    /// tests (default `https://api.github.com`).
    pub fn release_api_url(&self, api_base: &str) -> String {
        if self.tag == "latest" {
            format!(
                "{}/repos/{}/{}/releases/latest",
                api_base.trim_end_matches('/'),
                self.owner,
                self.repo
            )
        } else {
            format!(
                "{}/repos/{}/{}/releases/tags/{}",
                api_base.trim_end_matches('/'),
                self.owner,
                self.repo,
                self.tag
            )
        }
    }
}

/// Default GitHub API base URL. Override via the
/// `NEXO_GITHUB_API_BASE` env or in tests with a wiremock URL.
pub const DEFAULT_GITHUB_API_BASE: &str = "https://api.github.com";

/// One asset entry from the GitHub Releases API response.
/// Internal-only; the parser maps these into `ExtDownload` /
/// `ExtSigning`.
#[derive(Debug, Clone, serde::Deserialize)]
struct ReleaseAsset {
    name: String,
    browser_download_url: String,
    #[serde(default)]
    size: u64,
}

/// Top-level shape of a GitHub Releases API response. Only the
/// fields we consume.
#[derive(Debug, Clone, serde::Deserialize)]
struct ReleaseResponse {
    tag_name: String,
    #[serde(default)]
    assets: Vec<ReleaseAsset>,
}

/// Successful resolution of a release into an installable
/// entry. Carries enough info to call [`download_and_verify`].
#[derive(Debug, Clone)]
pub struct ResolvedInstall {
    /// Plugin entry built from the GitHub release.
    pub entry: ExtEntry,
    /// Index of the matching download in `entry.downloads`.
    pub download_index: usize,
    /// URL of the per-tarball `.sha256` asset (single line of
    /// hex). Used by `download_and_verify` to obtain the
    /// expected digest at install time.
    pub sha256_url: String,
}

/// Successful install — verified tarball on disk.
#[derive(Debug, Clone)]
pub struct InstalledTarball {
    /// On-disk path of the tarball.
    pub tarball_path: PathBuf,
    /// The plugin entry that was installed.
    pub entry: ExtEntry,
    /// Bytes downloaded.
    pub size_bytes: u64,
}

/// Generic resolve result carrying the typed manifest produced
/// by an [`ExtractContract`]. Contracts are free to attach any
/// in-process meaning to `manifest`; the resolver only stores
/// it. URL/size/signing fields are pre-resolved so the caller
/// can call [`download_and_verify_url`] without re-querying the
/// release JSON.
///
/// Lets persona-installer share the resolve+download pipeline
/// without duplicating the GitHub Releases plumbing.
#[derive(Debug, Clone)]
pub struct ResolvedReleaseTyped<M> {
    /// The typed manifest produced by [`ExtractContract::parse_manifest`].
    pub manifest: M,
    /// Coords echoed back so callers building entries don't have
    /// to thread them separately.
    pub coords: RepoCoords,
    /// Semver parsed from the release `tag_name` (`v` stripped).
    pub version: semver::Version,
    /// Target triple actually matched. May differ from the
    /// caller's request when the resolver fell back to the
    /// `noarch` tarball.
    pub target: String,
    /// URL of the matched tarball asset.
    pub tarball_url: String,
    /// Size of the matched tarball asset in bytes (from the
    /// release JSON; not authoritative — verify against the
    /// downloaded body).
    pub tarball_size: u64,
    /// URL of the manifest asset (re-exposed so callers can
    /// echo it into their entry types).
    pub manifest_url: String,
    /// URL of the per-tarball `.sha256` asset (single line of
    /// hex). Used by [`download_and_verify_url`] to obtain the
    /// expected digest at install time.
    pub sha256_url: String,
    /// Optional cosign material (signature verification enforces it).
    pub signing: Option<nexo_ext_registry::ExtSigning>,
}

/// Fetch a release JSON from GitHub. Wraps the raw JSON in our
/// `ReleaseResponse` for the resolver to consume.
async fn fetch_release_raw(
    client: &reqwest::Client,
    coords: &RepoCoords,
    api_base: &str,
) -> Result<ReleaseResponse, InstallError> {
    let url = coords.release_api_url(api_base);
    let response = client
        .get(&url)
        .header("Accept", "application/vnd.github+json")
        .header("User-Agent", "nexo-ext-installer")
        .send()
        .await
        .map_err(|e| InstallError::Http(format!("fetch release: {e}")))?;
    if !response.status().is_success() {
        return Err(InstallError::Http(format!(
            "fetch release: HTTP {} for {}",
            response.status(),
            url
        )));
    }
    let json = response
        .json::<ReleaseResponse>()
        .await
        .map_err(|e| InstallError::Http(format!("decode release: {e}")))?;
    Ok(json)
}

/// Resolve a release into a downloadable entry parameterized
/// by an [`ExtractContract`]. The contract decides which
/// manifest asset to fetch and how to parse it; everything
/// else (semver from tag, tarball naming with `<id>-<version>-
/// <target>.tar.gz` shape, `noarch` fallback, sha256 sibling
/// lookup, cosign material) is shared across all contracts.
///
/// Steps:
/// 1. Fetch the release JSON.
/// 2. Parse semver from `tag_name` (strip leading `v`).
/// 3. Locate the manifest asset by `contract.manifest_asset_name()`.
/// 4. Download + parse the manifest via `contract.parse_manifest()`.
/// 5. Extract id via `contract.manifest_id()` for tarball naming.
/// 6. Find the tarball asset for `target`, fall back to `noarch`.
/// 7. Find the matching `.sha256` asset.
/// 8. Locate optional cosign material.
pub async fn resolve_release_with_contract<C: ExtractContract>(
    contract: &C,
    client: &reqwest::Client,
    coords: &RepoCoords,
    target: &str,
    api_base: &str,
) -> Result<ResolvedReleaseTyped<C::Manifest>, InstallError> {
    let release = fetch_release_raw(client, coords, api_base).await?;
    let version_str = release.tag_name.trim_start_matches('v').to_string();
    let version = semver::Version::parse(&version_str).map_err(|e| InstallError::ReleaseShape {
        owner: coords.owner.clone(),
        repo: coords.repo.clone(),
        reason: format!(
            "release tag `{}` does not parse as semver `vX.Y.Z`: {e}",
            release.tag_name
        ),
    })?;

    // Locate the manifest asset (filename declared by contract).
    let manifest_asset_name = contract.manifest_asset_name();
    let manifest_asset = release
        .assets
        .iter()
        .find(|a| a.name == manifest_asset_name)
        .ok_or_else(|| InstallError::ReleaseShape {
            owner: coords.owner.clone(),
            repo: coords.repo.clone(),
            reason: format!(
                "release `{}` is missing required asset `{manifest_asset_name}`",
                release.tag_name
            ),
        })?;

    // Fetch manifest bytes, hand off to contract for typed parse.
    let manifest_bytes = client
        .get(&manifest_asset.browser_download_url)
        .header("User-Agent", "nexo-ext-installer")
        .send()
        .await
        .map_err(|e| InstallError::Http(format!("fetch manifest: {e}")))?
        .bytes()
        .await
        .map_err(|e| InstallError::Http(format!("read manifest body: {e}")))?;
    let manifest = contract.parse_manifest(&manifest_bytes, coords)?;
    let pkg_id = contract.manifest_id(&manifest);

    // Find the tarball asset for the requested target. `noarch`
    // acts as a fallback target name so portable plugins
    // (Python, TypeScript) can publish a single asset that all
    // daemons accept.
    let per_target_name = format!("{pkg_id}-{version_str}-{target}.tar.gz");
    let noarch_name = format!("{pkg_id}-{version_str}-noarch.tar.gz");
    let (tarball_asset, tarball_name, matched_target) =
        match release.assets.iter().find(|a| a.name == per_target_name) {
            Some(a) => (a, per_target_name, target.to_string()),
            None => match release.assets.iter().find(|a| a.name == noarch_name) {
                Some(a) => (a, noarch_name, "noarch".to_string()),
                None => {
                    let available: Vec<String> = release
                        .assets
                        .iter()
                        .filter(|a| a.name.ends_with(".tar.gz"))
                        .map(|a| a.name.clone())
                        .collect();
                    return Err(InstallError::TargetNotFound {
                        id: pkg_id.clone(),
                        version: version.clone(),
                        target: target.to_string(),
                        available,
                    });
                }
            },
        };

    // Find the matching .sha256 asset.
    let sha256_name = format!("{tarball_name}.sha256");
    let sha256_asset = release
        .assets
        .iter()
        .find(|a| a.name == sha256_name)
        .ok_or_else(|| InstallError::ReleaseShape {
            owner: coords.owner.clone(),
            repo: coords.repo.clone(),
            reason: format!(
                "release `{}` is missing required asset `{sha256_name}` for tarball `{tarball_name}`",
                release.tag_name
            ),
        })?;

    // Locate optional cosign material (signature verification enforces it).
    let sig_name = format!("{tarball_name}.sig");
    let cert_name = format!("{tarball_name}.cert");
    let signing = match (
        release.assets.iter().find(|a| a.name == sig_name),
        release.assets.iter().find(|a| a.name == cert_name),
    ) {
        (Some(sig), Some(cert)) => Some(nexo_ext_registry::ExtSigning {
            cosign_signature_url: sig.browser_download_url.clone(),
            cosign_certificate_url: cert.browser_download_url.clone(),
        }),
        _ => None,
    };

    Ok(ResolvedReleaseTyped {
        manifest,
        coords: coords.clone(),
        version,
        target: matched_target,
        tarball_url: tarball_asset.browser_download_url.clone(),
        tarball_size: tarball_asset.size,
        manifest_url: manifest_asset.browser_download_url.clone(),
        sha256_url: sha256_asset.browser_download_url.clone(),
        signing,
    })
}

/// Resolve a plugin's release into a downloadable entry. Thin
/// adapter over [`resolve_release_with_contract`] using
/// [`PluginExtractContract`]; preserved for backward compat
/// with all existing callers (`src/plugin_install.rs`,
/// `src/plugin_admin.rs`).
///
/// Steps:
/// 1. Fetch the release JSON.
/// 2. Locate the `nexo-plugin.toml` asset.
/// 3. Download + parse the manifest to learn `plugin.id`.
/// 4. Find the tarball asset matching the requested `target`
///    using the naming convention
///    `<id>-<version>-<target>.tar.gz`.
/// 5. Find the matching `.sha256` asset.
/// 6. Build an `ExtEntry` with one download.
pub async fn resolve_release(
    client: &reqwest::Client,
    coords: &RepoCoords,
    target: &str,
    api_base: &str,
) -> Result<ResolvedInstall, InstallError> {
    let resolved =
        resolve_release_with_contract(&PluginExtractContract, client, coords, target, api_base)
            .await?;

    // Per the decentralized model, every release defaults
    // to `tier = community`. Operator's trusted_keys.toml decides
    // which authors' cosign keys count as "verified" at install
    // time.
    //
    // `downloads[0].target` echoes the *requested* target rather
    // than the matched asset's flavor (`noarch` vs per-target).
    // Preserves pre-refactor behavior; the typed `resolved.target`
    // field exposes the truth to contract-aware callers.
    let entry = ExtEntry {
        id: resolved.manifest.plugin.id.clone(),
        version: resolved.version,
        name: resolved.manifest.plugin.name.clone(),
        description: resolved.manifest.plugin.description.clone(),
        homepage: format!("https://github.com/{}/{}", coords.owner, coords.repo),
        tier: nexo_ext_registry::ExtTier::Community,
        min_nexo_version: resolved.manifest.plugin.min_nexo_version.clone(),
        downloads: vec![nexo_ext_registry::ExtDownload {
            target: target.to_string(),
            url: resolved.tarball_url,
            // Placeholder: actual sha256 hex is read from the
            // `.sha256` asset at download time. Putting the
            // GitHub asset URL here would be wrong (URLs aren't
            // hex). Use a well-known sentinel + the downloader
            // overrides with the fetched value before the
            // expected/got compare.
            sha256: "from_sha256_asset_at_download".to_string(),
            size_bytes: resolved.tarball_size,
        }],
        manifest_url: resolved.manifest_url,
        signing: resolved.signing,
        authors: Vec::new(),
    };

    Ok(ResolvedInstall {
        entry,
        download_index: 0,
        sha256_url: resolved.sha256_url,
    })
}

/// URL-based download+verify primitive. Fetches the expected
/// sha256 from `sha256_url`, streams the tarball from
/// `tarball_url` to `dest_path`, and rejects on mismatch
/// (cleaning up the partial file). Returns the byte count.
///
/// Decoupled from [`ResolvedInstall`] so `persona-installer`
/// can drive download without constructing an
/// `ExtEntry`. Plugin path uses [`download_and_verify`] which
/// is now a thin wrapper.
///
/// `pkg_id_for_errors` is echoed verbatim into
/// [`InstallError::Sha256Invalid`] / [`InstallError::Sha256Mismatch`]
/// so CLI output references the package the operator asked
/// for, not a generic "tarball" string.
pub async fn download_and_verify_url(
    client: &reqwest::Client,
    tarball_url: &str,
    sha256_url: &str,
    pkg_id_for_errors: &str,
    dest_path: &Path,
) -> Result<u64, InstallError> {
    if let Some(parent) = dest_path.parent() {
        if !parent.as_os_str().is_empty() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| InstallError::Io(format!("mkdir parent: {e}")))?;
        }
    }

    // Fetch expected sha256 from the .sha256 asset. Convention:
    // single line of lowercase hex (64 chars) with optional
    // trailing whitespace.
    let expected_sha = client
        .get(sha256_url)
        .header("User-Agent", "nexo-ext-installer")
        .send()
        .await
        .map_err(|e| InstallError::Http(format!("fetch sha256: {e}")))?
        .text()
        .await
        .map_err(|e| InstallError::Http(format!("read sha256 body: {e}")))?
        .split_whitespace()
        .next()
        .unwrap_or("")
        .to_lowercase();
    if expected_sha.len() != 64 || !expected_sha.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(InstallError::Sha256Invalid {
            id: pkg_id_for_errors.to_string(),
            got: expected_sha,
        });
    }

    let response = client
        .get(tarball_url)
        .header("User-Agent", "nexo-ext-installer")
        .send()
        .await
        .map_err(|e| InstallError::Http(format!("fetch tarball: {e}")))?;
    if !response.status().is_success() {
        return Err(InstallError::Http(format!(
            "fetch tarball: HTTP {}",
            response.status()
        )));
    }

    let mut hasher = Sha256::new();
    let mut size: u64 = 0;
    let mut file = tokio::fs::File::create(dest_path)
        .await
        .map_err(|e| InstallError::Io(format!("create dest: {e}")))?;
    let mut stream = response.bytes_stream();
    while let Some(chunk_res) = stream.next().await {
        let chunk = match chunk_res {
            Ok(c) => c,
            Err(e) => {
                drop(file);
                let _ = tokio::fs::remove_file(dest_path).await;
                return Err(InstallError::Http(format!("download chunk: {e}")));
            }
        };
        hasher.update(&chunk);
        size += chunk.len() as u64;
        if let Err(e) = file.write_all(&chunk).await {
            drop(file);
            let _ = tokio::fs::remove_file(dest_path).await;
            return Err(InstallError::Io(format!("write tarball: {e}")));
        }
    }
    file.flush()
        .await
        .map_err(|e| InstallError::Io(format!("flush tarball: {e}")))?;
    drop(file);

    let computed = hex::encode(hasher.finalize());
    if computed != expected_sha {
        let _ = tokio::fs::remove_file(dest_path).await;
        return Err(InstallError::Sha256Mismatch {
            id: pkg_id_for_errors.to_string(),
            expected: expected_sha,
            got: computed,
        });
    }
    Ok(size)
}

/// Download the resolved tarball, fetch the expected sha256
/// from its `.sha256` sibling, stream-verify the downloaded
/// bytes' digest matches. Aborts and removes the partial file
/// if the digest doesn't match. Thin wrapper over
/// [`download_and_verify_url`].
pub async fn download_and_verify(
    client: &reqwest::Client,
    resolved: &ResolvedInstall,
    dest_path: &Path,
) -> Result<InstalledTarball, InstallError> {
    let download = &resolved.entry.downloads[resolved.download_index];
    let size = download_and_verify_url(
        client,
        &download.url,
        &resolved.sha256_url,
        &resolved.entry.id,
        dest_path,
    )
    .await?;
    Ok(InstalledTarball {
        tarball_path: dest_path.to_path_buf(),
        entry: resolved.entry.clone(),
        size_bytes: size,
    })
}

/// One-shot helper: parse coords, fetch release, resolve,
/// download, verify. Equivalent to chaining the lower-level
/// functions but matches typical CLI usage.
pub async fn install_plugin(
    client: &reqwest::Client,
    coords: &str,
    target: &str,
    dest_path: &Path,
    api_base: &str,
) -> Result<InstalledTarball, InstallError> {
    let coords = RepoCoords::parse(coords)?;
    let resolved = resolve_release(client, &coords, target, api_base).await?;
    download_and_verify(client, &resolved, dest_path).await
}

/// Detect the running daemon's target triple. Override via
/// `NEXO_INSTALL_TARGET` env.
pub fn current_target_triple() -> String {
    if let Ok(t) = std::env::var("NEXO_INSTALL_TARGET") {
        if !t.is_empty() {
            return t;
        }
    }
    if cfg!(all(target_arch = "x86_64", target_os = "linux")) {
        "x86_64-unknown-linux-gnu".to_string()
    } else if cfg!(all(target_arch = "aarch64", target_os = "linux")) {
        "aarch64-unknown-linux-gnu".to_string()
    } else if cfg!(all(target_arch = "x86_64", target_os = "macos")) {
        "x86_64-apple-darwin".to_string()
    } else if cfg!(all(target_arch = "aarch64", target_os = "macos")) {
        "aarch64-apple-darwin".to_string()
    } else {
        "unknown-target".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn parse_coords_default_tag_latest() {
        let c = RepoCoords::parse("alice/plugin-x").unwrap();
        assert_eq!(c.owner, "alice");
        assert_eq!(c.repo, "plugin-x");
        assert_eq!(c.tag, "latest");
    }

    #[test]
    fn parse_coords_with_tag() {
        let c = RepoCoords::parse("alice/plugin-x@v0.2.0").unwrap();
        assert_eq!(c.owner, "alice");
        assert_eq!(c.repo, "plugin-x");
        assert_eq!(c.tag, "v0.2.0");
    }

    #[test]
    fn parse_coords_rejects_bad_shapes() {
        assert!(RepoCoords::parse("no-slash").is_err());
        assert!(RepoCoords::parse("/empty-owner").is_err());
        assert!(RepoCoords::parse("alice/").is_err());
        assert!(RepoCoords::parse("alice/plugin@").is_err());
        assert!(RepoCoords::parse("alice/plugin space@v1").is_err());
    }

    #[test]
    fn release_api_url_branches_on_tag() {
        let c = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        assert_eq!(
            c.release_api_url("https://api.github.com"),
            "https://api.github.com/repos/alice/x/releases/tags/v0.2.0"
        );
        let c2 = RepoCoords::parse("alice/x").unwrap();
        assert_eq!(
            c2.release_api_url("https://api.github.com"),
            "https://api.github.com/repos/alice/x/releases/latest"
        );
    }

    fn manifest_toml(id: &str, version: &str) -> String {
        format!(
            r#"[plugin]
id = "{id}"
version = "{version}"
name = "Slack Channel"
description = "Slack bot integration"
min_nexo_version = ">=0.0.1"

[plugin.requires]
nexo_capabilities = ["broker"]
"#
        )
    }

    /// Round-trip: fetch release, parse manifest from asset,
    /// resolve a target's tarball + sha256, download tarball,
    /// verify sha256 matches.
    #[tokio::test]
    async fn install_round_trip_with_real_sha() {
        let server = MockServer::start().await;

        let manifest_body = manifest_toml("slack", "0.2.0");
        let tarball_payload = b"fake plugin tarball bytes";
        let mut hasher = Sha256::new();
        hasher.update(tarball_payload);
        let tarball_sha = hex::encode(hasher.finalize());
        let sha_body = format!("{tarball_sha}\n");

        let manifest_url = format!("{}/manifest", server.uri());
        let tarball_url = format!("{}/tarball", server.uri());
        let sha_url = format!("{}/sha256", server.uri());

        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {
                    "name": "nexo-plugin.toml",
                    "browser_download_url": manifest_url,
                    "size": manifest_body.len()
                },
                {
                    "name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz",
                    "browser_download_url": tarball_url,
                    "size": tarball_payload.len()
                },
                {
                    "name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz.sha256",
                    "browser_download_url": sha_url,
                    "size": sha_body.len()
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/repos/alice/slack-plugin/releases/tags/v0.2.0"))
            .and(header("Accept", "application/vnd.github+json"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/manifest"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest_body.clone()))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/sha256"))
            .respond_with(ResponseTemplate::new(200).set_body_string(sha_body))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/tarball"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(tarball_payload.as_slice()))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/slack-plugin@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        let resolved = resolve_release(&client, &coords, "x86_64-unknown-linux-gnu", &server.uri())
            .await
            .expect("resolve");
        assert_eq!(resolved.entry.id, "slack");
        assert_eq!(resolved.entry.version.to_string(), "0.2.0");
        assert_eq!(resolved.entry.tier, nexo_ext_registry::ExtTier::Community);

        let tmp = tempfile::tempdir().unwrap();
        let dest = tmp.path().join("slack-0.2.0.tar.gz");
        let installed = download_and_verify(&client, &resolved, &dest)
            .await
            .expect("download");
        assert_eq!(installed.tarball_path, dest);
        assert_eq!(installed.size_bytes as usize, tarball_payload.len());
        assert!(dest.exists());
    }

    #[tokio::test]
    async fn rejects_release_missing_manifest_asset() {
        let server = MockServer::start().await;
        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {
                    "name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz",
                    "browser_download_url": "https://example.com/tar",
                    "size": 100
                }
                // no nexo-plugin.toml asset
            ]
        });
        Mock::given(method("GET"))
            .and(path("/repos/alice/x/releases/tags/v0.2.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        match resolve_release(&client, &coords, "x86_64-unknown-linux-gnu", &server.uri()).await {
            Err(InstallError::ReleaseShape { reason, .. }) => {
                assert!(reason.contains("nexo-plugin.toml"));
            }
            other => panic!("expected ReleaseShape error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn rejects_release_missing_target_tarball() {
        let server = MockServer::start().await;
        let manifest_body = manifest_toml("slack", "0.2.0");
        let manifest_url = format!("{}/manifest", server.uri());
        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {
                    "name": "nexo-plugin.toml",
                    "browser_download_url": manifest_url,
                    "size": manifest_body.len()
                },
                {
                    "name": "slack-0.2.0-aarch64-apple-darwin.tar.gz",
                    "browser_download_url": "https://example.com/tar",
                    "size": 100
                }
                // no x86_64 linux tarball
            ]
        });
        Mock::given(method("GET"))
            .and(path("/repos/alice/x/releases/tags/v0.2.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/manifest"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest_body))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        match resolve_release(&client, &coords, "x86_64-unknown-linux-gnu", &server.uri()).await {
            Err(InstallError::TargetNotFound { available, .. }) => {
                assert_eq!(
                    available,
                    vec!["slack-0.2.0-aarch64-apple-darwin.tar.gz".to_string()]
                );
            }
            other => panic!("expected TargetNotFound, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn resolve_release_falls_back_to_noarch_when_per_target_absent() {
        let server = MockServer::start().await;
        let manifest_body = manifest_toml("slack", "0.2.0");
        let manifest_url = format!("{}/manifest", server.uri());
        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {"name": "nexo-plugin.toml", "browser_download_url": manifest_url, "size": manifest_body.len()},
                // ONLY noarch — no per-target tarball.
                {"name": "slack-0.2.0-noarch.tar.gz", "browser_download_url": "https://example.com/tar", "size": 100},
                {"name": "slack-0.2.0-noarch.tar.gz.sha256", "browser_download_url": "https://example.com/sha", "size": 64}
            ]
        });
        Mock::given(method("GET"))
            .and(path("/repos/alice/x/releases/tags/v0.2.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/manifest"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest_body))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        let resolved = resolve_release(&client, &coords, "x86_64-unknown-linux-gnu", &server.uri())
            .await
            .expect("noarch fallback");
        assert_eq!(
            resolved.entry.downloads[0].url.as_str(),
            "https://example.com/tar"
        );
        assert!(resolved.sha256_url.contains("/sha"));
    }

    #[tokio::test]
    async fn resolve_release_prefers_per_target_over_noarch() {
        let server = MockServer::start().await;
        let manifest_body = manifest_toml("slack", "0.2.0");
        let manifest_url = format!("{}/manifest", server.uri());
        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {"name": "nexo-plugin.toml", "browser_download_url": manifest_url, "size": manifest_body.len()},
                {"name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz", "browser_download_url": "https://example.com/per-target", "size": 100},
                {"name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz.sha256", "browser_download_url": "https://example.com/per-sha", "size": 64},
                {"name": "slack-0.2.0-noarch.tar.gz", "browser_download_url": "https://example.com/noarch", "size": 100},
                {"name": "slack-0.2.0-noarch.tar.gz.sha256", "browser_download_url": "https://example.com/noarch-sha", "size": 64}
            ]
        });
        Mock::given(method("GET"))
            .and(path("/repos/alice/x/releases/tags/v0.2.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/manifest"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest_body))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        let resolved = resolve_release(&client, &coords, "x86_64-unknown-linux-gnu", &server.uri())
            .await
            .expect("per-target preferred");
        assert_eq!(
            resolved.entry.downloads[0].url.as_str(),
            "https://example.com/per-target",
            "per-target tarball must win when both present"
        );
    }

    #[tokio::test]
    async fn detects_sha256_mismatch_and_cleans_up() {
        let server = MockServer::start().await;
        let manifest_body = manifest_toml("slack", "0.2.0");
        let tarball_payload = b"actual bytes here";
        // ADVERTISE A WRONG sha256 — install must reject + remove.
        let advertised_sha = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n";

        let manifest_url = format!("{}/manifest", server.uri());
        let tarball_url = format!("{}/tarball", server.uri());
        let sha_url = format!("{}/sha256", server.uri());

        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {"name": "nexo-plugin.toml", "browser_download_url": manifest_url, "size": manifest_body.len()},
                {"name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz", "browser_download_url": tarball_url, "size": tarball_payload.len()},
                {"name": "slack-0.2.0-x86_64-unknown-linux-gnu.tar.gz.sha256", "browser_download_url": sha_url, "size": advertised_sha.len()}
            ]
        });
        Mock::given(method("GET"))
            .and(path("/repos/alice/x/releases/tags/v0.2.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/manifest"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest_body))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/sha256"))
            .respond_with(ResponseTemplate::new(200).set_body_string(advertised_sha))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/tarball"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(tarball_payload.as_slice()))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        let resolved = resolve_release(&client, &coords, "x86_64-unknown-linux-gnu", &server.uri())
            .await
            .expect("resolve");

        let tmp = tempfile::tempdir().unwrap();
        let dest = tmp.path().join("tampered.tar.gz");
        match download_and_verify(&client, &resolved, &dest).await {
            Err(InstallError::Sha256Mismatch { id, .. }) => assert_eq!(id, "slack"),
            other => panic!("expected Sha256Mismatch, got {other:?}"),
        }
        assert!(!dest.exists(), "partial file must be removed on mismatch");
    }

    // ─── ExtractContract abstraction tests ─────────────────────
    //
    // Exercise `resolve_release_with_contract` with a synthetic
    // contract that consumes a non-plugin manifest filename +
    // schema. Proves the resolver doesn't smuggle the
    // `nexo-plugin.toml` assumption anywhere — the persona-installer
    // crate plugs in its own contract analogously.

    #[derive(Debug, serde::Deserialize)]
    struct TestPersonaManifest {
        id: String,
        #[allow(dead_code)]
        name: String,
    }

    #[derive(Debug, Default, Clone, Copy)]
    struct TestPersonaContract;

    impl ExtractContract for TestPersonaContract {
        type Manifest = TestPersonaManifest;

        fn manifest_asset_name(&self) -> &'static str {
            "test-persona.toml"
        }

        fn parse_manifest(
            &self,
            bytes: &[u8],
            coords: &RepoCoords,
        ) -> Result<Self::Manifest, InstallError> {
            let text = std::str::from_utf8(bytes).map_err(|e| InstallError::ReleaseShape {
                owner: coords.owner.clone(),
                repo: coords.repo.clone(),
                reason: format!("test-persona manifest is not valid UTF-8: {e}"),
            })?;
            toml::from_str::<Self::Manifest>(text).map_err(|e| InstallError::ReleaseShape {
                owner: coords.owner.clone(),
                repo: coords.repo.clone(),
                reason: format!("test-persona manifest parse failed: {e}"),
            })
        }

        fn manifest_id(&self, m: &Self::Manifest) -> String {
            m.id.clone()
        }
    }

    /// Custom contract end-to-end: synthetic `test-persona.toml`
    /// asset is located, parsed via the contract, and the
    /// matching tarball + sha256 are resolved using the contract-
    /// supplied id.
    #[tokio::test]
    async fn resolve_release_with_contract_serves_custom_manifest_filename() {
        let server = MockServer::start().await;

        let manifest_body = r#"id = "cody"
name = "Cody Persona"
"#;
        let manifest_url = format!("{}/persona-toml", server.uri());
        let tarball_url = format!("{}/persona-tar", server.uri());
        let sha_url = format!("{}/persona-sha", server.uri());

        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {"name": "test-persona.toml", "browser_download_url": manifest_url, "size": manifest_body.len()},
                {"name": "cody-0.2.0-noarch.tar.gz", "browser_download_url": tarball_url, "size": 42},
                {"name": "cody-0.2.0-noarch.tar.gz.sha256", "browser_download_url": sha_url, "size": 64}
            ]
        });
        Mock::given(method("GET"))
            .and(path(
                "/repos/lordmacu/nexo-persona-cody/releases/tags/v0.2.0",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/persona-toml"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest_body))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("lordmacu/nexo-persona-cody@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        let resolved = resolve_release_with_contract(
            &TestPersonaContract,
            &client,
            &coords,
            "x86_64-unknown-linux-gnu",
            &server.uri(),
        )
        .await
        .expect("contract resolve");

        assert_eq!(resolved.manifest.id, "cody");
        assert_eq!(resolved.version.to_string(), "0.2.0");
        assert_eq!(
            resolved.target, "noarch",
            "noarch fallback wins when per-target absent"
        );
        assert_eq!(resolved.tarball_url.as_str(), tarball_url);
        assert_eq!(resolved.sha256_url.as_str(), sha_url);
        assert!(resolved.signing.is_none(), "no cosign assets in fixture");
    }

    /// Contract-driven manifest filename mismatch: release ships
    /// `nexo-plugin.toml` but our contract asks for
    /// `test-persona.toml`. Resolver must fail with
    /// `ReleaseShape` mentioning the *contract's* filename, not
    /// the plugin one.
    #[tokio::test]
    async fn resolve_release_with_contract_errors_when_contract_manifest_absent() {
        let server = MockServer::start().await;
        let release = json!({
            "tag_name": "v0.2.0",
            "assets": [
                {"name": "nexo-plugin.toml", "browser_download_url": "https://example.com/m", "size": 100}
                // no test-persona.toml
            ]
        });
        Mock::given(method("GET"))
            .and(path("/repos/alice/x/releases/tags/v0.2.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(release))
            .mount(&server)
            .await;

        let coords = RepoCoords::parse("alice/x@v0.2.0").unwrap();
        let client = reqwest::Client::new();
        match resolve_release_with_contract(
            &TestPersonaContract,
            &client,
            &coords,
            "x86_64-unknown-linux-gnu",
            &server.uri(),
        )
        .await
        {
            Err(InstallError::ReleaseShape { reason, .. }) => {
                assert!(
                    reason.contains("test-persona.toml"),
                    "error must mention contract-supplied filename, got: {reason}"
                );
                assert!(
                    !reason.contains("nexo-plugin.toml"),
                    "error must NOT leak the plugin filename, got: {reason}"
                );
            }
            other => panic!("expected ReleaseShape error, got {other:?}"),
        }
    }
}