jan-cli 0.27.0

YAML-defined CLI trees with progressive help, optional exec aliases, merged extra specs, and SQLite audit logging keyed by git branch
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
//! HTTPS fetch with SHA256 verification and TTL-based local caching (wgex-inspired).

use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use anyhow::{anyhow, bail, Context, Result};
use reqwest::blocking::Client;
use reqwest::header::{ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, USER_AGENT};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
use url::Url;

/// Default TTL for cached remote objects (24 hours).
pub const DEFAULT_TTL_SECS: u64 = 86_400;
/// Default max download size for a single object (20 MiB).
pub const DEFAULT_MAX_BYTES: u64 = 20 * 1024 * 1024;
/// Default HTTP timeout.
pub const DEFAULT_TIMEOUT_SECS: u64 = 20;

const USER_AGENT_VALUE: &str = concat!("jan-cli/", env!("CARGO_PKG_VERSION"));

#[derive(Debug, Clone)]
pub struct FetchOpts {
    pub ttl_secs: u64,
    pub max_bytes: u64,
    pub timeout_secs: u64,
    pub allow_http: bool,
}

impl FetchOpts {
    pub fn new() -> Self {
        Self {
            ttl_secs: DEFAULT_TTL_SECS,
            max_bytes: DEFAULT_MAX_BYTES,
            timeout_secs: DEFAULT_TIMEOUT_SECS,
            allow_http: allow_http_from_env(),
        }
    }

    pub fn with_ttl(mut self, ttl_secs: u64) -> Self {
        self.ttl_secs = ttl_secs;
        self
    }

    pub fn with_allow_http(mut self, allow: bool) -> Self {
        self.allow_http = allow;
        self
    }
}

impl Default for FetchOpts {
    fn default() -> Self {
        Self::new()
    }
}

fn allow_http_from_env() -> bool {
    matches!(
        std::env::var("JAN_ALLOW_HTTP").as_deref(),
        Ok("1") | Ok("true") | Ok("TRUE") | Ok("yes") | Ok("YES")
    )
}

#[derive(Serialize, Deserialize)]
struct CacheMetadata {
    downloaded_at: SystemTime,
    content_hash: String,
    etag: Option<String>,
    last_modified: Option<String>,
    url: String,
}

/// Cache root: `$JAN_CACHE_DIR` or `$XDG_CACHE_HOME/jan` (or platform equivalent).
pub fn cache_root() -> Result<PathBuf> {
    if let Ok(p) = std::env::var("JAN_CACHE_DIR") {
        let p = p.trim();
        if !p.is_empty() {
            let root = PathBuf::from(p);
            fs::create_dir_all(&root).with_context(|| format!("create {}", root.display()))?;
            return Ok(root);
        }
    }
    let base = dirs::cache_dir()
        .or_else(|| dirs::home_dir().map(|h| h.join(".cache")))
        .ok_or_else(|| anyhow!("could not resolve cache directory"))?;
    let root = base.join("jan");
    fs::create_dir_all(&root).with_context(|| format!("create {}", root.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&root)?.permissions();
        perms.set_mode(0o700);
        fs::set_permissions(&root, perms)?;
    }
    Ok(root)
}

pub fn objects_dir() -> Result<PathBuf> {
    let d = cache_root()?.join("objects");
    fs::create_dir_all(&d).with_context(|| format!("create {}", d.display()))?;
    Ok(d)
}

pub fn trees_dir() -> Result<PathBuf> {
    let d = cache_root()?.join("trees");
    fs::create_dir_all(&d).with_context(|| format!("create {}", d.display()))?;
    Ok(d)
}

pub fn normalize_sha256(s: &str) -> Result<String> {
    let s = s.trim().to_ascii_lowercase();
    if s.len() != 64 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
        bail!("sha256 must be a 64-character hex string");
    }
    Ok(s)
}

fn validate_url(url: &str, allow_http: bool) -> Result<Url> {
    let parsed = Url::parse(url).with_context(|| format!("invalid URL: {url}"))?;
    match parsed.scheme() {
        "https" => Ok(parsed),
        "http" if allow_http => Ok(parsed),
        "http" => bail!("refusing non-HTTPS URL (set JAN_ALLOW_HTTP=1 or pass --allow-http)"),
        other => bail!("unsupported URL scheme `{other}` (only https is allowed by default)"),
    }
}

fn build_client(timeout_secs: u64) -> Result<Client> {
    Client::builder()
        .timeout(Duration::from_secs(timeout_secs))
        .redirect(reqwest::redirect::Policy::limited(5))
        .user_agent(USER_AGENT_VALUE)
        .build()
        .context("build HTTP client")
}

fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

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

pub fn sha256_file(path: &Path) -> Result<String> {
    let mut file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 32 * 1024];
    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hex_encode(&hasher.finalize()))
}

/// Verify `path` contents match `expected` (64-char hex). Returns Ok on match.
pub fn verify_file_sha256(path: &Path, expected: &str) -> Result<()> {
    let expected = normalize_sha256(expected)?;
    let got = sha256_file(path)?;
    if got != expected {
        bail!(
            "SHA256 mismatch for {}: expected {expected}, got {got}",
            path.display()
        );
    }
    Ok(())
}

fn verify_file_hash(path: &Path, expected: &str) -> Result<bool> {
    Ok(sha256_file(path)? == expected)
}

fn write_metadata(path: &Path, meta: &CacheMetadata) {
    if let Ok(s) = serde_json::to_string(meta) {
        let _ = fs::write(path, s);
    }
}

fn persist_temp_to_cache(temp_path: &Path, cache_path: &Path) -> Result<()> {
    if let Some(parent) = cache_path.parent() {
        fs::create_dir_all(parent)?;
    }
    match fs::rename(temp_path, cache_path) {
        Ok(()) => Ok(()),
        Err(_) => {
            fs::copy(temp_path, cache_path)?;
            let _ = fs::remove_file(temp_path);
            Ok(())
        }
    }
}

#[cfg(unix)]
fn make_executable(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = fs::metadata(path)?.permissions();
    perms.set_mode(perms.mode() | 0o100);
    fs::set_permissions(path, perms)?;
    Ok(())
}

#[cfg(not(unix))]
fn make_executable(_path: &Path) -> Result<()> {
    Ok(())
}

enum FetchResult {
    NotModified,
    Downloaded {
        temp_path: PathBuf,
        etag: Option<String>,
        last_modified: Option<String>,
        sha256: String,
    },
}

fn fetch_conditional(
    client: &Client,
    url: &str,
    metadata: Option<&CacheMetadata>,
    max_bytes: u64,
) -> Result<FetchResult> {
    let mut req = client.get(url);
    if let Some(m) = metadata {
        if let Some(ref etag) = m.etag {
            req = req.header(IF_NONE_MATCH, etag.clone());
        }
        if let Some(ref lm) = m.last_modified {
            req = req.header(IF_MODIFIED_SINCE, lm.clone());
        }
    }
    let mut resp = req.header(USER_AGENT, USER_AGENT_VALUE).send()?;
    if resp.status() == reqwest::StatusCode::NOT_MODIFIED {
        return Ok(FetchResult::NotModified);
    }
    if !resp.status().is_success() {
        bail!("HTTP error: {}", resp.status());
    }
    if let Some(len) = resp.content_length() {
        if len > max_bytes {
            bail!("content too large ({len} bytes > max {max_bytes})");
        }
    }

    let mut hasher = Sha256::new();
    let mut tmp = NamedTempFile::new()?;
    let mut total: u64 = 0;
    let mut buf = [0u8; 16 * 1024];
    loop {
        let n = resp.read(&mut buf)?;
        if n == 0 {
            break;
        }
        total += n as u64;
        if total > max_bytes {
            bail!("exceeded max bytes {max_bytes}");
        }
        hasher.update(&buf[..n]);
        tmp.write_all(&buf[..n])?;
    }
    let sha256 = hex_encode(&hasher.finalize());
    let etag = resp
        .headers()
        .get(ETAG)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());
    let last_modified = resp
        .headers()
        .get(LAST_MODIFIED)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());
    let (_file, temp_path) = tmp.keep()?;
    Ok(FetchResult::Downloaded {
        temp_path,
        etag,
        last_modified,
        sha256,
    })
}

/// Fetch `url`, verify against `expected_sha256`, and return the cached file path.
///
/// When `executable` is true, sets the executable bit on Unix (for remote scripts).
pub fn fetch_verified(
    url: &str,
    expected_sha256: &str,
    opts: &FetchOpts,
    executable: bool,
) -> Result<PathBuf> {
    let expected = normalize_sha256(expected_sha256)?;
    validate_url(url, opts.allow_http)?;
    let client = build_client(opts.timeout_secs)?;
    let cache_dir = objects_dir()?;
    let cache_file = cache_dir.join(&expected);
    let metadata_path = cache_dir.join(format!("{expected}.meta"));

    let mut metadata: Option<CacheMetadata> = None;
    if let Ok(s) = fs::read_to_string(&metadata_path) {
        if let Ok(m) = serde_json::from_str::<CacheMetadata>(&s) {
            metadata = Some(m);
        }
    }

    let mut cache_ok = false;
    if cache_file.exists() {
        match verify_file_hash(&cache_file, &expected) {
            Ok(true) => cache_ok = true,
            Ok(false) => {
                let _ = fs::remove_file(&cache_file);
            }
            Err(_) => {
                let _ = fs::remove_file(&cache_file);
            }
        }
    }

    let mut cache_fresh = false;
    if cache_ok {
        if let Some(ref m) = metadata {
            if let Ok(elapsed) = m.downloaded_at.elapsed() {
                if elapsed < Duration::from_secs(opts.ttl_secs) {
                    cache_fresh = true;
                }
            }
        }
    }

    if !cache_fresh {
        match fetch_conditional(&client, url, metadata.as_ref(), opts.max_bytes) {
            Ok(FetchResult::NotModified) => {
                if let Some(mut m) = metadata.take() {
                    m.downloaded_at = SystemTime::now();
                    write_metadata(&metadata_path, &m);
                }
                cache_ok = true;
            }
            Ok(FetchResult::Downloaded {
                temp_path,
                etag,
                last_modified,
                sha256,
            }) => {
                if sha256 == expected {
                    persist_temp_to_cache(&temp_path, &cache_file)?;
                    if executable {
                        make_executable(&cache_file)?;
                    }
                    let new_meta = CacheMetadata {
                        downloaded_at: SystemTime::now(),
                        content_hash: expected.clone(),
                        etag,
                        last_modified,
                        url: url.to_string(),
                    };
                    write_metadata(&metadata_path, &new_meta);
                    cache_ok = true;
                } else {
                    let _ = fs::remove_file(&temp_path);
                    if !cache_ok {
                        bail!("SHA256 mismatch for {url}: expected {expected}, got {sha256}");
                    }
                    // Keep existing valid cache if remote drifted.
                }
            }
            Err(e) => {
                if !cache_ok {
                    return Err(e).with_context(|| format!("fetch {url}"));
                }
            }
        }
    }

    if !cache_ok {
        // Full download path when no usable cache.
        match fetch_conditional(&client, url, None, opts.max_bytes)? {
            FetchResult::NotModified => unreachable!("no validators"),
            FetchResult::Downloaded {
                temp_path,
                etag,
                last_modified,
                sha256,
            } => {
                if sha256 != expected {
                    let _ = fs::remove_file(&temp_path);
                    bail!("SHA256 mismatch for {url}: expected {expected}, got {sha256}");
                }
                persist_temp_to_cache(&temp_path, &cache_file)?;
                if executable {
                    make_executable(&cache_file)?;
                }
                let new_meta = CacheMetadata {
                    downloaded_at: SystemTime::now(),
                    content_hash: expected.clone(),
                    etag,
                    last_modified,
                    url: url.to_string(),
                };
                write_metadata(&metadata_path, &new_meta);
            }
        }
    }

    if executable {
        make_executable(&cache_file)?;
    }
    Ok(cache_file)
}

/// Read verified remote content as a UTF-8 string (for YAML includes).
pub fn fetch_verified_text(url: &str, expected_sha256: &str, opts: &FetchOpts) -> Result<String> {
    let path = fetch_verified(url, expected_sha256, opts, false)?;
    fs::read_to_string(&path).with_context(|| format!("read cached {}", path.display()))
}

/// Whether a string looks like an http(s) URL suitable for `jan use`.
pub fn looks_like_remote_url(s: &str) -> bool {
    let s = s.trim();
    s.starts_with("https://") || s.starts_with("http://")
}

// ---------------------------------------------------------------------------
// Bundle zip: verify + safe extract into ~/.cache/jan/trees/<sha256>/
// ---------------------------------------------------------------------------

const MAX_MANIFEST_SIZE: u64 = 1024 * 1024;
const MAX_MEMBER_SIZE: u64 = 128 * 1024 * 1024;
const MAX_TOTAL_SIZE: u64 = 512 * 1024 * 1024;

#[derive(Debug, Deserialize)]
struct BundleManifest {
    root_yaml: String,
    files: serde_json::Map<String, serde_json::Value>,
}

fn validate_member_name(name: &str) -> Result<()> {
    if name.is_empty() || name.contains('\\') {
        bail!("unsafe ZIP member path: {name:?}");
    }
    let path = Path::new(name);
    if path.is_absolute() {
        bail!("unsafe ZIP member path: {name:?}");
    }
    for part in path.components() {
        match part {
            std::path::Component::Normal(s) => {
                let s = s.to_string_lossy();
                if s.is_empty() || s == "." || s == ".." {
                    bail!("unsafe ZIP member path: {name:?}");
                }
            }
            std::path::Component::CurDir | std::path::Component::ParentDir => {
                bail!("unsafe ZIP member path: {name:?}");
            }
            _ => bail!("unsafe ZIP member path: {name:?}"),
        }
    }
    let canonical = path
        .components()
        .map(|c| c.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/");
    if canonical != name.trim_end_matches('/') {
        bail!("non-canonical ZIP member path: {name:?}");
    }
    Ok(())
}

/// Download a jan bundle zip, verify the zip SHA256, verify manifest members, unpack
/// under `~/.cache/jan/trees/<sha256>/`, and return `(tree_dir, root_yaml)`.
pub fn fetch_and_install_bundle(
    url: &str,
    zip_sha256: &str,
    opts: &FetchOpts,
) -> Result<(PathBuf, String)> {
    let expected = normalize_sha256(zip_sha256)?;
    // Zips can be larger than a single script object.
    let mut zip_opts = opts.clone();
    zip_opts.max_bytes = MAX_TOTAL_SIZE;
    let zip_path = fetch_verified(url, &expected, &zip_opts, false)?;

    let tree_dir = trees_dir()?.join(&expected);
    let marker = tree_dir.join(".jan-tree-ready");
    if tree_dir.is_dir() && marker.is_file() {
        let root = fs::read_to_string(&marker)?.trim().to_string();
        if !root.is_empty() && tree_dir.join(&root).is_file() {
            return Ok((tree_dir, root));
        }
    }

    // Re-extract into a staging dir then atomically replace.
    if tree_dir.exists() {
        fs::remove_dir_all(&tree_dir)
            .with_context(|| format!("remove stale tree {}", tree_dir.display()))?;
    }

    let parent = tree_dir
        .parent()
        .ok_or_else(|| anyhow!("trees dir has no parent"))?
        .to_path_buf();
    let staging = parent.join(format!(".staging-{expected}"));
    if staging.exists() {
        fs::remove_dir_all(&staging)?;
    }
    fs::create_dir_all(&staging)?;

    let root_yaml = extract_verified_bundle(&zip_path, &staging)?;
    // Atomic-ish replace
    if tree_dir.exists() {
        fs::remove_dir_all(&tree_dir)?;
    }
    fs::rename(&staging, &tree_dir)
        .with_context(|| format!("move staging to {}", tree_dir.display()))?;
    fs::write(&marker, format!("{root_yaml}\n"))?;
    Ok((tree_dir, root_yaml))
}

fn extract_verified_bundle(zip_path: &Path, dest: &Path) -> Result<String> {
    let file = File::open(zip_path).with_context(|| format!("open {}", zip_path.display()))?;
    let mut archive = zip::ZipArchive::new(file).context("open zip archive")?;

    let mut by_name: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    let mut total_size: u64 = 0;
    for i in 0..archive.len() {
        let entry = archive.by_index(i)?;
        let name = entry.name().to_string();
        let is_dir = entry.is_dir();
        let name_for_check = if is_dir {
            name.trim_end_matches('/').to_string()
        } else {
            name.clone()
        };
        if !name_for_check.is_empty() {
            validate_member_name(&name_for_check)?;
        }
        let key = if is_dir {
            format!("{}/", name_for_check)
        } else {
            name_for_check.clone()
        };
        if by_name.contains_key(&key) || by_name.contains_key(&name_for_check) {
            bail!("duplicate ZIP member: {name_for_check}");
        }
        if entry.size() > MAX_MEMBER_SIZE {
            bail!("ZIP member too large: {name_for_check}");
        }
        total_size = total_size.saturating_add(entry.size());
        if total_size > MAX_TOTAL_SIZE {
            bail!("bundle exceeds extraction size limit");
        }
        by_name.insert(name_for_check, i);
    }

    // Read manifest
    let manifest_idx = *by_name
        .get("manifest.json")
        .ok_or_else(|| anyhow!("bundle is missing root manifest.json"))?;
    let mut manifest_entry = archive.by_index(manifest_idx)?;
    if manifest_entry.size() > MAX_MANIFEST_SIZE {
        bail!("manifest.json is too large");
    }
    let mut manifest_bytes = Vec::new();
    manifest_entry
        .read_to_end(&mut manifest_bytes)
        .context("read manifest.json")?;
    drop(manifest_entry);

    let manifest: BundleManifest =
        serde_json::from_slice(&manifest_bytes).context("invalid manifest.json")?;
    if manifest.files.is_empty() {
        bail!("manifest.json must contain a non-empty files object");
    }
    if !manifest.files.contains_key(&manifest.root_yaml) {
        bail!("manifest root_yaml must identify a listed file");
    }

    let mut listed: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for (name, expected) in &manifest.files {
        validate_member_name(name)?;
        let obj = expected
            .as_object()
            .ok_or_else(|| anyhow!("invalid manifest file entry: {name:?}"))?;
        let digest = obj
            .get("sha256")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow!("invalid manifest hash for {name}"))?;
        normalize_sha256(digest)?;
        let size = obj
            .get("size")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| anyhow!("invalid manifest size for {name}"))?;
        let idx = by_name
            .get(name.as_str())
            .ok_or_else(|| anyhow!("manifest file missing from ZIP: {name}"))?;
        let entry = archive.by_index(*idx)?;
        if entry.is_dir() {
            bail!("manifest file missing from ZIP: {name}");
        }
        if entry.size() != size {
            bail!("manifest size mismatch for {name}");
        }
        listed.insert(name.clone());
    }

    let required_metadata: std::collections::BTreeSet<&str> =
        ["manifest.json", "env.sh"].into_iter().collect();
    for meta in &required_metadata {
        if !by_name.contains_key(*meta) {
            bail!("bundle missing required metadata: {meta}");
        }
    }

    let mut allowed_dirs: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    let mut path_seeds: Vec<String> = listed.iter().cloned().collect();
    for meta in &required_metadata {
        path_seeds.push((*meta).to_string());
    }
    for name in &path_seeds {
        let mut parent = Path::new(name).parent();
        while let Some(p) = parent {
            let s = p.to_string_lossy().replace('\\', "/");
            if s.is_empty() || s == "." {
                break;
            }
            allowed_dirs.insert(s);
            parent = p.parent();
        }
    }

    for name in by_name.keys() {
        // Directory entries may appear with or without trailing slash in our map keys (no slash).
        let is_listed = listed.contains(name) || required_metadata.contains(name.as_str());
        if is_listed {
            continue;
        }
        // Treat as directory placeholder only if it is an allowed dir and we never extract content.
        if allowed_dirs.contains(name) {
            continue;
        }
        // Check if this key corresponds to a dir-only entry in the archive
        let idx = by_name[name];
        let entry = archive.by_index(idx)?;
        if entry.is_dir() {
            if !allowed_dirs.contains(name) {
                bail!("unlisted directory in bundle: {name}");
            }
        } else {
            bail!("unlisted file in bundle: {name}");
        }
    }

    // Extract all members
    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let raw_name = entry.name().to_string();
        let is_dir = entry.is_dir();
        let name = raw_name.trim_end_matches('/').to_string();
        if name.is_empty() {
            continue;
        }
        let target = dest.join(Path::new(&name));
        if is_dir {
            fs::create_dir_all(&target)?;
            continue;
        }
        if let Some(parent) = target.parent() {
            fs::create_dir_all(parent)?;
        }
        let mut hasher = Sha256::new();
        let mut out =
            File::create(&target).with_context(|| format!("create {}", target.display()))?;
        let mut size: u64 = 0;
        let mut buf = [0u8; 1024 * 1024];
        loop {
            let n = entry.read(&mut buf)?;
            if n == 0 {
                break;
            }
            size += n as u64;
            if size > MAX_MEMBER_SIZE {
                bail!("ZIP member expanded past limit: {name}");
            }
            hasher.update(&buf[..n]);
            out.write_all(&buf[..n])?;
        }
        if let Some(expected) = manifest.files.get(&name) {
            let obj = expected.as_object().unwrap();
            let digest = obj.get("sha256").and_then(|v| v.as_str()).unwrap();
            let expected_size = obj.get("size").and_then(|v| v.as_u64()).unwrap();
            let got = hex_encode(&hasher.finalize());
            if size != expected_size || got != digest.to_ascii_lowercase() {
                bail!("manifest verification failed for {name}");
            }
        }
    }

    Ok(manifest.root_yaml)
}

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

    #[test]
    fn normalize_sha256_rejects_bad() {
        assert!(normalize_sha256("abc").is_err());
        assert!(normalize_sha256(&"a".repeat(64)).is_ok());
    }

    #[test]
    fn looks_like_remote() {
        assert!(looks_like_remote_url("https://example.com/a.zip"));
        assert!(looks_like_remote_url("http://example.com/a.zip"));
        assert!(!looks_like_remote_url("/tmp/foo"));
        assert!(!looks_like_remote_url("ftp://x"));
    }

    #[test]
    fn validate_member_rejects_traversal() {
        assert!(validate_member_name("../etc/passwd").is_err());
        assert!(validate_member_name("/abs").is_err());
        assert!(validate_member_name("ok/path.yaml").is_ok());
    }

    #[test]
    fn sha256_hex_stable() {
        assert_eq!(
            sha256_hex(b"hello"),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn fetch_verified_from_local_http() {
        use std::io::Write as _;
        use std::net::TcpListener;
        use std::sync::Mutex;
        use std::thread;

        static LOCK: Mutex<()> = Mutex::new(());
        let _g = LOCK.lock().unwrap();

        let body = b"#!/bin/sh\necho hi\n";
        let digest = sha256_hex(body);
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let handle = thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut buf = [0u8; 1024];
            let _ = stream.read(&mut buf);
            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            );
            stream.write_all(resp.as_bytes()).unwrap();
            stream.write_all(body).unwrap();
        });

        let cache = tempfile::tempdir().unwrap();
        std::env::set_var("JAN_CACHE_DIR", cache.path());
        let url = format!("http://{addr}/script.sh");
        let opts = FetchOpts::new().with_allow_http(true);
        let path = fetch_verified(&url, &digest, &opts, true).unwrap();
        assert_eq!(fs::read(&path).unwrap(), body);
        std::env::remove_var("JAN_CACHE_DIR");
        handle.join().unwrap();
    }

    #[test]
    fn extract_bundle_roundtrip() {
        use zip::write::FileOptions;
        use zip::CompressionMethod;

        let tmp = tempfile::tempdir().unwrap();
        let zip_path = tmp.path().join("b.zip");
        let yaml = b"commands:\n  hi:\n    exec:\n      argv: [\"echo\", \"hi\"]\n";
        let yaml_hash = sha256_hex(yaml);
        let mut files = serde_json::Map::new();
        files.insert(
            "scripts.spec.yaml".into(),
            serde_json::json!({ "sha256": yaml_hash, "size": yaml.len() }),
        );
        let manifest = serde_json::json!({
            "root_yaml": "scripts.spec.yaml",
            "files": files,
        });
        let manifest_bytes = serde_json::to_vec_pretty(&manifest).unwrap();

        {
            let file = File::create(&zip_path).unwrap();
            let mut z = zip::ZipWriter::new(file);
            let opts =
                FileOptions::<'_, ()>::default().compression_method(CompressionMethod::Stored);
            z.start_file("scripts.spec.yaml", opts).unwrap();
            z.write_all(yaml).unwrap();
            z.start_file("env.sh", opts).unwrap();
            z.write_all(b"# env\n").unwrap();
            z.start_file("manifest.json", opts).unwrap();
            z.write_all(&manifest_bytes).unwrap();
            z.finish().unwrap();
        }

        let dest = tmp.path().join("out");
        fs::create_dir_all(&dest).unwrap();
        let root = extract_verified_bundle(&zip_path, &dest).unwrap();
        assert_eq!(root, "scripts.spec.yaml");
        assert_eq!(fs::read(dest.join("scripts.spec.yaml")).unwrap(), yaml);
    }
}