nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
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
//! Verified archive download, tar-slip/zip-slip pre-validation, symlink escape checking,
//! RAII temp cleanup, and atomic rotate-to-backup directory swap.

use std::fs;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

use super::sha256::{is_valid_sha256_hex, parse_sha256sums_for_file, sha256_file_hex};

static SDK_STAGE_SEQ: AtomicU64 = AtomicU64::new(1);

pub(crate) fn ends_with_ignore_ascii_case(haystack: &str, suffix: &str) -> bool {
    haystack.len() >= suffix.len()
        && haystack.as_bytes()[haystack.len() - suffix.len()..].eq_ignore_ascii_case(suffix.as_bytes())
}

/// Strips URL `#fragment` and `?query` suffixes and returns a safe archive basename.
pub(crate) fn extract_archive_filename(url_or_path: &str) -> String {
    let no_frag = url_or_path.split('#').next().unwrap_or(url_or_path);
    let no_query = no_frag.split('?').next().unwrap_or(no_frag);
    let candidate = no_query
        .rsplit(['/', '\\'])
        .next()
        .map(str::trim)
        .unwrap_or_default();
    if candidate.is_empty()
        || candidate == "."
        || candidate == ".."
        || candidate.contains('\0')
        || candidate.contains(':')
    {
        "artifact.tar.gz".to_owned()
    } else {
        candidate.to_owned()
    }
}

/// Validates that `raw` is a safe relative path strictly within an archive or SDK root:
/// rejects empty paths, NUL bytes, leading `/` or `\`, Windows drive prefixes (`C:...`),
/// and any `..` path traversal component.
pub fn validate_relative_sdk_path(raw: &str) -> Result<PathBuf, String> {
    if raw.is_empty() {
        return Err("path must not be empty".to_owned());
    }
    if raw.contains('\0') {
        return Err(format!("path '{raw}' contains NUL byte"));
    }
    if raw.starts_with('/') || raw.starts_with('\\') {
        return Err(format!("absolute path '{raw}' is not allowed"));
    }
    let bytes = raw.as_bytes();
    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
        return Err(format!("drive-prefixed path '{raw}' is not allowed"));
    }
    let mut normalized = PathBuf::new();
    for segment in raw.split(['/', '\\']) {
        if segment.is_empty() || segment == "." {
            continue;
        }
        if segment == ".." {
            return Err(format!("path traversal '..' in '{raw}' is not allowed"));
        }
        normalized.push(segment);
    }
    for comp in normalized.components() {
        if !matches!(comp, Component::Normal(_)) {
            return Err(format!("non-relative path component in '{raw}' is not allowed"));
        }
    }
    Ok(normalized)
}

/// Checks whether a symlink at relative path `link_rel` pointing to `target` stays inside root.
pub(crate) fn validate_relative_symlink_target(link_rel: &Path, target: &str) -> Result<(), String> {
    if target.is_empty() || target.contains('\0') {
        return Err(format!(
            "invalid symlink target '{target}' for '{}'",
            link_rel.display()
        ));
    }
    if target.starts_with('/') || target.starts_with('\\') {
        return Err(format!(
            "escaping absolute symlink '{}' -> '{target}' is not allowed",
            link_rel.display()
        ));
    }
    let bytes = target.as_bytes();
    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
        return Err(format!(
            "escaping drive-prefixed symlink '{}' -> '{target}' is not allowed",
            link_rel.display()
        ));
    }
    let mut depth: isize = link_rel
        .parent()
        .map(|p| {
            p.components()
                .filter(|c| matches!(c, Component::Normal(_)))
                .count() as isize
        })
        .unwrap_or(0);
    for seg in target.split(['/', '\\']) {
        if seg.is_empty() || seg == "." {
            continue;
        }
        if seg == ".." {
            depth -= 1;
            if depth < 0 {
                return Err(format!(
                    "escaping symlink '{}' -> '{target}' traverses outside archive root",
                    link_rel.display()
                ));
            }
        } else {
            depth += 1;
        }
    }
    Ok(())
}

/// RAII cleanup guard for a temporary file or directory.
pub(crate) struct TempPathGuard {
    path: Option<PathBuf>,
    is_dir: bool,
}

impl TempPathGuard {
    pub(crate) fn file(path: PathBuf) -> Self {
        Self { path: Some(path), is_dir: false }
    }

    pub(crate) fn dir(path: PathBuf) -> Self {
        Self { path: Some(path), is_dir: true }
    }

    pub(crate) fn path(&self) -> &Path {
        self.path.as_deref().unwrap_or_else(|| Path::new(""))
    }

    pub(crate) fn disarm(&mut self) {
        self.path = None;
    }
}

impl Drop for TempPathGuard {
    fn drop(&mut self) {
        if let Some(p) = self.path.take() {
            if self.is_dir {
                let _ = fs::remove_dir_all(p);
            } else {
                let _ = fs::remove_file(p);
            }
        }
    }
}

/// Atomically swaps `stage` into `dest` using rotate-to-backup + rollback on rename failure.
pub(crate) fn swap_dir_atomic(stage: &Path, dest: &Path) -> Result<(), String> {
    let parent = dest
        .parent()
        .ok_or_else(|| format!("invalid destination '{}'", dest.display()))?;
    let seq = SDK_STAGE_SEQ.fetch_add(1, Ordering::Relaxed);
    let backup = parent.join(format!(
        ".{}.prev-{}-{seq}",
        dest.file_name().and_then(|n| n.to_str()).unwrap_or("sdk"),
        std::process::id()
    ));
    let had_dest = dest.exists();
    if had_dest {
        fs::rename(dest, &backup).map_err(|e| {
            format!(
                "failed to rotate '{}' -> '{}': {e}",
                dest.display(),
                backup.display()
            )
        })?;
    }
    if let Err(err) = fs::rename(stage, dest) {
        if had_dest {
            let _ = fs::rename(&backup, dest);
        }
        return Err(format!(
            "failed to move '{}' -> '{}': {err}",
            stage.display(),
            dest.display()
        ));
    }
    if had_dest {
        let _ = fs::remove_dir_all(&backup);
    }
    Ok(())
}

/// Pre-validates archive entries BEFORE extraction to prevent tar-slip, zip-slip, and escaping links.
pub(crate) fn validate_archive_before_extract(archive: &Path) -> Result<(), String> {
    let name = archive
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();

    if ends_with_ignore_ascii_case(name, ".zip") {
        if cfg!(windows) {
            return validate_tar_entries(archive, &["-tf"], &["-tvf"]);
        }
        let out = Command::new("unzip")
            .args(["-Z", "-1"])
            .arg(archive)
            .output()
            .map_err(|e| format!("failed to inspect zip '{}': {e}", archive.display()))?;
        if !out.status.success() {
            return Err(format!(
                "inspecting zip archive '{}' failed ({})",
                archive.display(),
                out.status
            ));
        }
        for line in String::from_utf8_lossy(&out.stdout).lines() {
            let entry = line.trim_end_matches('\r');
            if !entry.is_empty() {
                validate_relative_sdk_path(entry)?;
            }
        }
        return Ok(());
    }

    if ends_with_ignore_ascii_case(name, ".tar.zst") {
        validate_tar_entries(archive, &["--zstd", "-tf"], &["--zstd", "-tvf"])
    } else {
        validate_tar_entries(archive, &["-tf"], &["-tvf"])
    }
}

fn validate_tar_entries(archive: &Path, list_args: &[&str], verbose_args: &[&str]) -> Result<(), String> {
    let list_out = Command::new("tar")
        .args(list_args)
        .arg(archive)
        .output()
        .map_err(|e| format!("failed to inspect archive '{}': {e}", archive.display()))?;
    if !list_out.status.success() {
        return Err(format!(
            "inspecting archive '{}' failed ({})",
            archive.display(),
            list_out.status
        ));
    }
    for line in String::from_utf8_lossy(&list_out.stdout).lines() {
        let entry = line.trim_end_matches('\r');
        if !entry.is_empty() {
            validate_relative_sdk_path(entry)?;
        }
    }

    let verbose_out = Command::new("tar")
        .args(verbose_args)
        .arg(archive)
        .output()
        .map_err(|e| format!("failed to inspect archive metadata '{}': {e}", archive.display()))?;
    if verbose_out.status.success() {
        for line in String::from_utf8_lossy(&verbose_out.stdout).lines() {
            let trimmed = line.trim_end_matches('\r');
            if trimmed.starts_with('l') {
                if let Some((before, target)) = trimmed.rsplit_once(" -> ") {
                    let link_path = before.split_whitespace().last().unwrap_or_default();
                    let rel = validate_relative_sdk_path(link_path)?;
                    validate_relative_symlink_target(&rel, target)?;
                } else {
                    return Err(format!(
                        "unparseable symlink entry in archive '{}': '{trimmed}'",
                        archive.display()
                    ));
                }
            } else if trimmed.starts_with('h')
                && let Some((_, target)) = trimmed.rsplit_once(" link to ")
            {
                validate_relative_sdk_path(target)?;
            }
        }
    }
    Ok(())
}

/// Defense-in-depth post-extraction walk verifying no symlink inside `root` escapes `root`.
fn validate_extracted_symlinks(root: &Path, dir: &Path) -> Result<(), String> {
    let entries = fs::read_dir(dir)
        .map_err(|e| format!("failed to scan extracted dir '{}': {e}", dir.display()))?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("failed to read extracted entry: {e}"))?;
        let path = entry.path();
        let meta = fs::symlink_metadata(&path)
            .map_err(|e| format!("failed to stat '{}': {e}", path.display()))?;
        let rel = path.strip_prefix(root).unwrap_or(&path);
        if meta.file_type().is_symlink() {
            let target = fs::read_link(&path)
                .map_err(|e| format!("failed to read symlink '{}': {e}", path.display()))?;
            let target_str = target.to_str().ok_or_else(|| {
                format!("non-UTF-8 symlink target at '{}' is not allowed", rel.display())
            })?;
            validate_relative_symlink_target(rel, target_str)?;
        } else if meta.is_dir() {
            validate_extracted_symlinks(root, &path)?;
        }
    }
    Ok(())
}

/// Validates and extracts `.tar.gz`, `.tar.zst`, `.tar.xz`, or `.zip` into `dest_dir`.
pub fn extract_archive(archive: &Path, dest_dir: &Path) -> Result<(), String> {
    validate_archive_before_extract(archive)?;
    fs::create_dir_all(dest_dir)
        .map_err(|e| format!("failed to create '{}': {e}", dest_dir.display()))?;
    let name = archive
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();
    let status = if ends_with_ignore_ascii_case(name, ".zip") {
        if cfg!(windows) {
            Command::new("tar")
                .args(["-xf"])
                .arg(archive)
                .arg("-C")
                .arg(dest_dir)
                .status()
        } else {
            Command::new("unzip")
                .args(["-q", "-o"])
                .arg(archive)
                .arg("-d")
                .arg(dest_dir)
                .status()
        }
    } else if ends_with_ignore_ascii_case(name, ".tar.zst") {
        Command::new("tar")
            .args(["--zstd", "-xf"])
            .arg(archive)
            .arg("-C")
            .arg(dest_dir)
            .status()
    } else {
        Command::new("tar")
            .args(["-xf"])
            .arg(archive)
            .arg("-C")
            .arg(dest_dir)
            .status()
    }
    .map_err(|e| format!("failed to extract '{}': {e}", archive.display()))?;
    if !status.success() {
        return Err(format!(
            "extracting '{}' into '{}' failed with {status}",
            archive.display(),
            dest_dir.display()
        ));
    }
    validate_extracted_symlinks(dest_dir, dest_dir)?;
    Ok(())
}

fn try_fetch_url_text(url: &str) -> Option<String> {
    let out = Command::new("curl")
        .args(["-fsSL", "--retry", "2", url])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    String::from_utf8(out.stdout).ok()
}

/// Automatically resolves the expected SHA-256 digest from sibling `SHA256SUMS.txt` or
/// `<archive>.sha256` next to a local path or release URL.
pub(crate) fn resolve_auto_sha256(url_or_path: &str, archive_filename: &str) -> Option<String> {
    let local_path = url_or_path
        .strip_prefix("file://")
        .map(PathBuf::from)
        .or_else(|| {
            let p = Path::new(url_or_path);
            p.is_file().then(|| p.to_path_buf())
        });
    if let Some(path) = local_path {
        let sidecar = PathBuf::from(format!("{}.sha256", path.display()));
        if let Ok(text) = fs::read_to_string(&sidecar)
            && let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, true)
        {
            return Some(hex);
        }
        if let Some(dir) = path.parent() {
            for sums_name in ["SHA256SUMS.txt", "SHA256SUMS"] {
                if let Ok(text) = fs::read_to_string(dir.join(sums_name))
                    && let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, false)
                {
                    return Some(hex);
                }
            }
        }
        return None;
    }

    // Remote URL: strip #fragment and ?query to probe sibling SHA256SUMS.txt and <archive>.sha256.
    let no_frag = url_or_path.split('#').next().unwrap_or(url_or_path);
    let no_query = no_frag.split('?').next().unwrap_or(no_frag);
    if let Some(slash) = no_query.rfind('/') {
        let base_dir = &no_query[..=slash];
        if let Some(text) = try_fetch_url_text(&format!("{base_dir}SHA256SUMS.txt"))
            && let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, false)
        {
            return Some(hex);
        }
    }
    if let Some(text) = try_fetch_url_text(&format!("{no_query}.sha256"))
        && let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, true)
    {
        return Some(hex);
    }
    None
}

/// Downloads `url_or_path` (or copies a local `file://` / filesystem path), requires and verifies
/// SHA-256 (either explicit or auto-resolved from `SHA256SUMS.txt`/`.sha256`), pre-validates
/// archive entries against tar-slip/zip-slip, and atomically swaps into `dest_dir`.
pub fn fetch_and_extract_verified(
    url_or_path: &str,
    expected_sha256: Option<&str>,
    dest_dir: &Path,
) -> Result<(), String> {
    fetch_and_extract_verified_with_policy(url_or_path, expected_sha256, false, dest_dir)
}

/// Same as [`fetch_and_extract_verified`] with explicit `allow_unverified` opt-in for local
/// unsigned archives when no checksum is available.
pub fn fetch_and_extract_verified_with_policy(
    url_or_path: &str,
    expected_sha256: Option<&str>,
    allow_unverified: bool,
    dest_dir: &Path,
) -> Result<(), String> {
    let parent = dest_dir
        .parent()
        .ok_or_else(|| format!("invalid cache destination '{}'", dest_dir.display()))?;
    fs::create_dir_all(parent)
        .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;

    let filename = extract_archive_filename(url_or_path);
    let seq = SDK_STAGE_SEQ.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    let tmp_archive_guard = TempPathGuard::file(parent.join(format!(".nv-dl-{pid}-{seq}-{filename}")));
    let mut tmp_stage_guard = TempPathGuard::dir(parent.join(format!(".nv-stage-{pid}-{seq}-{filename}")));

    if let Some(local) = url_or_path.strip_prefix("file://") {
        fs::copy(local, tmp_archive_guard.path())
            .map_err(|e| format!("failed to copy '{local}': {e}"))?;
    } else if Path::new(url_or_path).is_file() {
        fs::copy(url_or_path, tmp_archive_guard.path())
            .map_err(|e| format!("failed to copy '{url_or_path}': {e}"))?;
    } else {
        let status = Command::new("curl")
            .args(["-fsSL", "--retry", "3", "-o"])
            .arg(tmp_archive_guard.path())
            .arg(url_or_path)
            .status()
            .map_err(|e| format!("failed to spawn `curl` for '{url_or_path}': {e}"))?;
        if !status.success() {
            return Err(format!("`curl` failed fetching '{url_or_path}' ({status})"));
        }
    }

    let explicit = expected_sha256.map(str::trim).filter(|s| !s.is_empty());
    let resolved_sha = match explicit {
        Some(hex) => {
            if !is_valid_sha256_hex(hex) {
                return Err(format!(
                    "invalid --sha256 digest '{hex}' for '{url_or_path}' (expected 64 hex chars)"
                ));
            }
            #[expect(
                clippy::disallowed_methods,
                reason = "cold CLI SDK install path normalizing an explicit 64-char SHA-256 hex digest"
            )]
            Some(hex.to_ascii_lowercase())
        }
        None => resolve_auto_sha256(url_or_path, &filename),
    };

    match resolved_sha {
        Some(expected) => {
            let actual = sha256_file_hex(tmp_archive_guard.path())?;
            if !actual.eq_ignore_ascii_case(&expected) {
                return Err(format!(
                    "SHA-256 mismatch for '{url_or_path}': expected {expected}, got {actual}"
                ));
            }
        }
        None if allow_unverified => {
            eprintln!("warning: skipping SHA-256 verification for '{url_or_path}' (--allow-unverified)");
        }
        None => {
            return Err(format!(
                "SHA-256 verification is required for '{url_or_path}' (no --sha256 given and no SHA256SUMS.txt or .sha256 found; pass --sha256 <HEX> or --allow-unverified)"
            ));
        }
    }

    extract_archive(tmp_archive_guard.path(), tmp_stage_guard.path())?;
    drop(tmp_archive_guard);

    // Unwrap a single top-level wrapper directory if present (e.g. `nativeview-sdk-v0.1.0/`).
    let content_root = unwrap_single_dir(tmp_stage_guard.path());
    let moving_stage_itself = content_root == tmp_stage_guard.path();
    swap_dir_atomic(&content_root, dest_dir)?;
    if moving_stage_itself {
        tmp_stage_guard.disarm();
    }
    Ok(())
}

fn unwrap_single_dir(dir: &Path) -> PathBuf {
    let Ok(rd) = fs::read_dir(dir) else {
        return dir.to_path_buf();
    };
    let entries: Vec<PathBuf> = rd.filter_map(|e| e.ok().map(|x| x.path())).collect();
    if entries.len() == 1
        && entries[0].is_dir()
        && !fs::symlink_metadata(&entries[0]).is_ok_and(|m| m.file_type().is_symlink())
        && entries[0]
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| !n.ends_with(".xcframework"))
    {
        entries[0].clone()
    } else {
        dir.to_path_buf()
    }
}