hugincyber 0.2.18

Installer for Hugin — an intercepting proxy, web scanner, and bug bounty toolkit in a single binary (GUI + CLI).
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
use std::io::{self, Cursor, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

use serde::Deserialize;
use sha2::{Digest, Sha256};

const GITHUB_API: &str =
    "https://api.github.com/repos/HuginCyber/Hugin/releases/latest";
/// Forgejo releases API endpoint — canonical source, proxied through nginx
/// on hugin.nu (port 443). Port 3000 is not exposed publicly, so the
/// previous `http://hugin.nu:3000/...` fallback always timed out. Mirrors
/// `hugin-service::updater::FORGEJO_API_RELEASES_LATEST`.
const FORGEJO_API: &str =
    "https://hugin.nu/api/v1/repos/andrei/hugin/releases/latest";
/// CDN base for release asset downloads. All `browser_download_url`
/// values returned by the GitHub/Forgejo API are rewritten to this host so
/// downloads go through our CDN (nginx static) instead of GitHub's
/// rate-limited CDN — the 110 MB+ binary otherwise stalls. The SHA256
/// sidecar is still verified after download, so this is not a trust
/// boundary. Mirrors `hugin_service::updater::rewrite_download_urls`.
const HUGIN_CDN_BASE: &str = "https://hugin.nu/releases";
const USER_AGENT: &str = concat!("hugincyber-installer/", env!("CARGO_PKG_VERSION"));

#[derive(Deserialize)]
struct Release {
    tag_name: String,
    assets: Vec<Asset>,
}

#[derive(Deserialize)]
struct Asset {
    name: String,
    browser_download_url: String,
    size: u64,
}

/// The asset we want for this platform. Returns the filename prefix
/// (e.g. "hugin-cli-darwin-aarch64") — we match it flexibly against
/// whatever the release actually published (with or without .tar.gz).
fn asset_prefix() -> Result<&'static str, String> {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;

    match (os, arch) {
        ("linux", "x86_64") => Ok("hugin-cli-linux-x86_64"),
        ("macos", "aarch64") => Ok("hugin-cli-darwin-aarch64"),
        ("macos", "x86_64") => Ok("hugin-cli-darwin-x86_64"),
        ("linux", "aarch64") => Err(
            "Linux aarch64 is not yet available. Vote via GitHub star: \
             https://github.com/HuginCyber/Hugin"
                .into(),
        ),
        ("windows", _) => Err(
            "Windows is not planned. Hugin runs on Linux and macOS.".into(),
        ),
        (os, arch) => Err(format!(
            "Unsupported platform: {os}-{arch}. \
             Hugin runs on linux-x86_64, macos-aarch64, and macos-x86_64."
        )),
    }
}

fn install_dir() -> Result<PathBuf, String> {
    if let Some(home) = std::env::var_os("HOME") {
        let local_bin = Path::new(&home).join(".local").join("bin");
        if local_bin.exists() || std::fs::create_dir_all(&local_bin).is_ok() {
            return Ok(local_bin);
        }
    }
    if std::env::consts::OS == "macos" {
        let usr_local = Path::new("/usr/local/bin");
        if usr_local.exists() {
            return Ok(usr_local.to_path_buf());
        }
    }
    Err(
        "Could not find a writable install directory. \
         Set HOME or ensure ~/.local/bin or /usr/local/bin is writable."
            .into(),
    )
}

fn http_client() -> Result<reqwest::blocking::Client, String> {
    reqwest::blocking::Client::builder()
        .user_agent(USER_AGENT)
        .build()
        .map_err(|e| format!("Failed to build HTTP client: {e}"))
}

fn fetch_release_from(url: &str) -> Result<Release, String> {
    let resp = http_client()?
        .get(url)
        .header("Accept", "application/json")
        .send()
        .map_err(|e| format!("Failed to fetch release info from {url}: {e}"))?;

    if !resp.status().is_success() {
        return Err(format!(
            "{url} returned HTTP {} {}",
            resp.status().as_u16(),
            resp.status().canonical_reason().unwrap_or("error")
        ));
    }

    resp.json::<Release>()
        .map_err(|e| format!("Failed to parse release JSON from {url}: {e}"))
}

/// Rewrite all asset download URLs to point at the hugin.nu CDN.
///
/// The GitHub/Forgejo API returns `browser_download_url` pointing at their
/// own CDNs (e.g. `https://github.com/.../releases/download/v0.2.15/...`).
/// These are slow, rate-limited, and time out for large binaries (110MB+).
/// We serve the same files from `https://hugin.nu/releases/<tag>/` via
/// nginx static — fast, no rate limit, no WAF. The SHA256 sidecar is still
/// verified after download, so this is not a trust boundary.
fn rewrite_download_urls(release: &mut Release) {
    let tag = &release.tag_name;
    for asset in &mut release.assets {
        let cdn_url = format!("{HUGIN_CDN_BASE}/{tag}/{}", asset.name);
        asset.browser_download_url = cdn_url;
    }
}

/// Try GitHub first, fall back to Forgejo. Returns the release + which
/// source it came from (for display). All asset download URLs are
/// rewritten to the hugin.nu CDN regardless of which API served the
/// metadata.
fn fetch_release() -> Result<(Release, &'static str), String> {
    match fetch_release_from(GITHUB_API) {
        Ok(mut r) => {
            rewrite_download_urls(&mut r);
            Ok((r, "GitHub"))
        }
        Err(github_err) => {
            eprintln!("  \x1b[33mGitHub unavailable:\x1b[0m {github_err}");
            eprintln!("  \x1b[33mFalling back to Forgejo...\x1b[0m");
            match fetch_release_from(FORGEJO_API) {
                Ok(mut r) => {
                    rewrite_download_urls(&mut r);
                    Ok((r, "Forgejo"))
                }
                Err(e) => Err(e),
            }
        }
    }
}

/// Find the asset matching our platform prefix. Accepts both
/// `hugin-cli-{platform}.tar.gz` and bare `hugin-cli-{platform}`.
fn find_asset<'a>(release: &'a Release, prefix: &str) -> Result<&'a Asset, String> {
    // Prefer .tar.gz if available
    let tarball_name = format!("{prefix}.tar.gz");
    if let Some(a) = release.assets.iter().find(|a| a.name == tarball_name) {
        return Ok(a);
    }
    // Fall back to bare binary (no .tar.gz extension)
    if let Some(a) = release.assets.iter().find(|a| a.name == prefix) {
        return Ok(a);
    }
    // Last resort: any asset starting with the prefix
    if let Some(a) = release
        .assets
        .iter()
        .find(|a| a.name.starts_with(prefix) && !a.name.ends_with(".sha256"))
    {
        return Ok(a);
    }
    Err(format!(
        "No matching asset '{prefix}' (or '{tarball_name}') in release {}.\n\
         Available assets:\n{}",
        release.tag_name,
        release
            .assets
            .iter()
            .map(|a| format!("  - {} ({} MB)", a.name, a.size / 1_048_576))
            .collect::<Vec<_>>()
            .join("\n")
    ))
}

/// Fetch the .sha256 sidecar for the asset (if it exists) and return the
/// expected hex digest.
fn fetch_sha256(release: &Release, asset_name: &str) -> Option<String> {
    let sha_name = format!("{asset_name}.sha256");
    let sha_asset = release.assets.iter().find(|a| a.name == sha_name)?;
    let resp = http_client().ok()?
        .get(&sha_asset.browser_download_url)
        .send()
        .ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let text = resp.text().ok()?;
    // sha256sum output: "<hex>  filename" — take the first token
    text.split_whitespace().next().map(|s| s.to_lowercase())
}

fn download_asset(url: &str) -> Result<Vec<u8>, String> {
    print!("  Downloading... ");
    io::stdout().flush().ok();

    let resp = http_client()?
        .get(url)
        .send()
        .map_err(|e| format!("Failed to download: {e}"))?;

    if !resp.status().is_success() {
        return Err(format!("Download failed: HTTP {}", resp.status()));
    }

    let bytes = resp
        .bytes()
        .map_err(|e| format!("Failed to read download: {e}"))?;

    println!("{} MB", bytes.len() / 1_048_576);
    Ok(bytes.to_vec())
}

fn verify_sha256(data: &[u8], expected_hex: &str) -> Result<(), String> {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let actual = hex::encode(hasher.finalize());
    if actual == expected_hex {
        Ok(())
    } else {
        Err(format!(
            "SHA256 mismatch!\n  expected: {expected_hex}\n  actual:   {actual}"
        ))
    }
}

/// Extract the `hugin` binary from a .tar.gz archive.
fn extract_from_tarball(archive: &[u8], dest: &Path) -> Result<PathBuf, String> {
    let cursor = Cursor::new(archive);
    let gz = flate2::read::GzDecoder::new(cursor);
    let mut tar = tar::Archive::new(gz);

    for entry in tar.entries().map_err(|e| format!("Failed to read tar: {e}"))? {
        let mut entry = entry.map_err(|e| format!("Failed to read tar entry: {e}"))?;
        let name = entry
            .path()
            .map_err(|e| format!("Failed to get entry path: {e}"))?
            .into_owned();

        if name.file_name() == Some(std::ffi::OsStr::new("hugin")) {
            let dest_path = dest.join("hugin");
            entry
                .unpack(dest)
                .map_err(|e| format!("Failed to extract hugin: {e}"))?;
            set_executable(&dest_path)?;
            return Ok(dest_path);
        }
    }
    Err("hugin binary not found in archive".into())
}

/// Write a bare binary (no archive) directly to the install dir.
fn write_bare_binary(data: &[u8], dest: &Path) -> Result<PathBuf, String> {
    let dest_path = dest.join("hugin");
    std::fs::write(&dest_path, data)
        .map_err(|e| format!("Failed to write binary: {e}"))?;
    set_executable(&dest_path)?;
    Ok(dest_path)
}

#[cfg(unix)]
fn set_executable(path: &Path) -> Result<(), String> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
        .map_err(|e| format!("Failed to set executable permissions: {e}"))
}

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

fn is_on_path(dir: &Path) -> bool {
    if let Ok(path_var) = std::env::var("PATH") {
        for entry in path_var.split(':') {
            if Path::new(entry) == dir {
                return true;
            }
        }
    }
    false
}

fn main() {
    let version = env!("CARGO_PKG_VERSION");
    println!("\n  \x1b[1;38;5;208mHuginCyber\x1b[0m installer v{version}\n");
    println!("  The security intercepting proxy for hackers.");
    println!("  https://hugin.nu\n");

    // 1. Detect platform
    let prefix = match asset_prefix() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
            std::process::exit(1);
        }
    };

    // 2. Fetch latest release (GitHub → Forgejo fallback)
    print!("  Checking latest release... ");
    io::stdout().flush().ok();
    let (release, _source) = match fetch_release() {
        Ok((r, src)) => {
            println!("{} (via {src})", r.tag_name);
            (r, src)
        }
        Err(e) => {
            eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
            std::process::exit(1);
        }
    };

    // 3. Find matching asset
    let asset = match find_asset(&release, prefix) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
            std::process::exit(1);
        }
    };

    // 4. Download
    let archive = match download_asset(&asset.browser_download_url) {
        Ok(data) => data,
        Err(e) => {
            eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
            std::process::exit(1);
        }
    };

    // 5. Verify SHA256 (if sidecar exists)
    if let Some(expected) = fetch_sha256(&release, &asset.name) {
        print!("  Verifying SHA256... ");
        io::stdout().flush().ok();
        match verify_sha256(&archive, &expected) {
            Ok(()) => println!("ok"),
            Err(e) => {
                eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
                std::process::exit(1);
            }
        }
    } else {
        eprintln!("  \x1b[33mWarning:\x1b[0m No SHA256 sidecar found — skipping verification.");
    }

    // 6. Install
    let install_dir = match install_dir() {
        Ok(dir) => dir,
        Err(e) => {
            eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
            std::process::exit(1);
        }
    };

    print!("  Extracting to {}... ", install_dir.display());
    io::stdout().flush().ok();
    let binary = if asset.name.ends_with(".tar.gz") {
        extract_from_tarball(&archive, &install_dir)
    } else {
        write_bare_binary(&archive, &install_dir)
    };
    let binary = match binary {
        Ok(p) => {
            println!("done");
            p
        }
        Err(e) => {
            eprintln!("\n  \x1b[31mError:\x1b[0m {e}");
            std::process::exit(1);
        }
    };

    // 7. Verify the binary runs
    if let Ok(output) = Command::new(&binary).arg("--version").output() {
        let v = String::from_utf8_lossy(&output.stdout);
        let v = v.lines().next().unwrap_or("(unknown version)");
        println!("\n  \x1b[32mInstalled:\x1b[0m {v}");
    } else {
        println!("\n  \x1b[32mInstalled:\x1b[0m {}", binary.display());
    }

    // 8. PATH check
    if !is_on_path(&install_dir) {
        eprintln!(
            "\n  \x1b[33mWarning:\x1b[0m {} is not on your PATH.",
            install_dir.display()
        );
        eprintln!("  Add it to your shell profile:");
        eprintln!("    export PATH=\"{}:$PATH\"", install_dir.display());
    }

    println!("\n  Run \x1b[1mhugin\x1b[0m to start.\n");
}

// Minimal hex encoder (avoids pulling a hex crate dependency).
mod hex {
    pub fn encode(bytes: impl AsRef<[u8]>) -> String {
        let bytes = bytes.as_ref();
        let mut s = String::with_capacity(bytes.len() * 2);
        for b in bytes {
            s.push_str(&format!("{b:02x}"));
        }
        s
    }
}

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

    #[test]
    fn rewrite_download_urls_points_to_cdn() {
        let mut release = Release {
            tag_name: "v0.2.15".to_owned(),
            assets: vec![
                Asset {
                    name: "hugin-cli-darwin-aarch64.tar.gz".to_owned(),
                    browser_download_url:
                        "https://github.com/HuginCyber/Hugin/releases/download/v0.2.15/hugin-cli-darwin-aarch64.tar.gz"
                            .to_owned(),
                    size: 110_997_572,
                },
                Asset {
                    name: "hugin-cli-darwin-aarch64.tar.gz.sha256".to_owned(),
                    browser_download_url:
                        "https://github.com/HuginCyber/Hugin/releases/download/v0.2.15/hugin-cli-darwin-aarch64.tar.gz.sha256"
                            .to_owned(),
                    size: 121,
                },
            ],
        };
        rewrite_download_urls(&mut release);
        assert_eq!(
            release.assets[0].browser_download_url,
            "https://hugin.nu/releases/v0.2.15/hugin-cli-darwin-aarch64.tar.gz"
        );
        assert_eq!(
            release.assets[1].browser_download_url,
            "https://hugin.nu/releases/v0.2.15/hugin-cli-darwin-aarch64.tar.gz.sha256"
        );
    }
}