Skip to main content

mj_controller/controller/
update.rs

1//! Install-aware startup update checks for `mj`.
2//!
3//! Mjolnir reaches users through several channels — the curl release
4//! installer, the npm package, the Homebrew tap, and crates.io — and each
5//! channel publishes its "latest" somewhere else. This module decides how
6//! the running binary was installed, asks that channel whether a newer
7//! release exists, and (in [`check_prompt_and_apply`]) asks the
8//! user before changing anything. npm and Homebrew upgrades delegate to the
9//! package manager; curl installs self-replace; cargo and npx installs only
10//! print the command, because a live `cargo install` rebuild or a nested
11//! `npx` run is not something to start from inside mj.
12
13use mj_core::hex::lower_hex;
14use std::ffi::OsString;
15use std::io::{self, BufRead, Cursor, IsTerminal, Read, Write};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18use std::time::Duration;
19
20use anyhow::{Context, Result, bail, ensure};
21use flate2::read::GzDecoder;
22use semver::Version;
23use serde::Deserialize;
24use sha2::{Digest, Sha256};
25
26const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/BrokkAi/mjolnir/releases/latest";
27const NPM_LATEST_URL: &str = "https://registry.npmjs.org/@brokkai%2Fmjolnir/latest";
28const HOMEBREW_FORMULA_URL: &str =
29    "https://raw.githubusercontent.com/BrokkAi/homebrew-tap/main/Formula/mjolnir.rb";
30const BIN_NAME: &str = "mj";
31const WINDOWS_BIN_NAME: &str = "mj.exe";
32const VOICE_WORKER_NAME: &str = "mj-voice-worker";
33const NPM_MANAGED_ENV: &str = "MJOLNIR_MANAGED_BY_NPM";
34const NPX_MANAGED_ENV: &str = "MJOLNIR_MANAGED_BY_NPX";
35const HOMEBREW_MANAGED_ENV: &str = "MJOLNIR_MANAGED_BY_HOMEBREW";
36const NO_UPDATE_CHECK_ENV: &str = "MJOLNIR_NO_UPDATE_CHECK";
37
38/// The endpoints a channel consults, grouped so loopback tests can point
39/// every fetch at a local server instead of the real registries.
40#[derive(Debug, Clone)]
41struct UpdateSources {
42    latest_release: String,
43    npm_latest: String,
44    homebrew_formula: String,
45    cargo_index: String,
46}
47
48impl Default for UpdateSources {
49    fn default() -> Self {
50        Self {
51            latest_release: LATEST_RELEASE_URL.to_string(),
52            npm_latest: NPM_LATEST_URL.to_string(),
53            homebrew_formula: HOMEBREW_FORMULA_URL.to_string(),
54            cargo_index: CARGO_INDEX_URL.to_string(),
55        }
56    }
57}
58
59/// How the running `mj` binary was installed. Decides both where the latest
60/// version is published and who is allowed to replace the binary: package
61/// managers own their trees, so upgrades there run the manager's own
62/// command, while a curl install may only be replaced in place.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum InstallMethod {
65    Npm,
66    Npx,
67    Homebrew,
68    Cargo { voice_worker: bool },
69    Direct,
70}
71
72impl InstallMethod {
73    /// Detects the install method from the launcher-declared environment
74    /// markers, falling back to executable-path forensics. The markers are
75    /// set by `npm/launcher/mj.js` and the Homebrew formula's wrapper script.
76    fn current() -> Self {
77        Self::detect(
78            |name| std::env::var_os(name),
79            std::env::current_exe().ok().as_deref(),
80        )
81    }
82
83    fn detect<F>(env: F, exe: Option<&Path>) -> Self
84    where
85        F: Fn(&str) -> Option<OsString>,
86    {
87        if env(NPX_MANAGED_ENV).is_some() {
88            return Self::Npx;
89        }
90        if env(NPM_MANAGED_ENV).is_some() {
91            return Self::Npm;
92        }
93        if env(HOMEBREW_MANAGED_ENV).is_some() {
94            return Self::Homebrew;
95        }
96        exe.map_or(Self::Direct, |exe| {
97            install_method_from_exe(exe, env!("CARGO_PKG_VERSION"))
98        })
99    }
100
101    /// The command a person would run to upgrade through this channel. Used
102    /// verbatim for the notice-only channels and as the basis for the
103    /// delegated upgrade of npm and Homebrew.
104    fn update_command(&self) -> Option<String> {
105        match self {
106            Self::Npm => Some("npm install -g @brokkai/mjolnir@latest".to_string()),
107            Self::Npx => Some("npx -y @brokkai/mjolnir@latest".to_string()),
108            Self::Homebrew => Some("brew upgrade mjolnir".to_string()),
109            Self::Cargo { voice_worker: true } => {
110                Some("cargo install --locked brokk-mjolnir brokk-mj-voice-worker".to_string())
111            }
112            Self::Cargo {
113                voice_worker: false,
114            } => Some("cargo install --locked brokk-mjolnir".to_string()),
115            Self::Direct => None,
116        }
117    }
118
119    fn channel_name(&self) -> &'static str {
120        match self {
121            Self::Npm | Self::Npx => "npm",
122            Self::Homebrew => "Homebrew",
123            Self::Cargo { .. } => "crates.io",
124            Self::Direct => "GitHub Releases",
125        }
126    }
127}
128
129fn install_method_from_exe(exe_path: &Path, current_version: &str) -> InstallMethod {
130    if is_homebrew_executable(exe_path) {
131        return InstallMethod::Homebrew;
132    }
133    if is_npm_bundle_executable(exe_path) {
134        return InstallMethod::Npm;
135    }
136
137    let Some(install_root) = cargo_install_root(exe_path, current_version) else {
138        return InstallMethod::Direct;
139    };
140    InstallMethod::Cargo {
141        voice_worker: cargo_install_recorded(
142            &install_root,
143            "brokk-mj-voice-worker",
144            None,
145            VOICE_WORKER_NAME,
146        ),
147    }
148}
149
150fn is_homebrew_executable(exe_path: &Path) -> bool {
151    let components = path_text_components(exe_path);
152    components
153        .windows(2)
154        .any(|pair| pair == ["Cellar", "mjolnir"])
155}
156
157/// Recognizes an npm bundle binary even when the launcher's marker is
158/// missing: without this, an env-less npm install would be misread as a
159/// direct install and the self-replace path would write inside
160/// `node_modules`, corrupting npm's package database.
161fn is_npm_bundle_executable(exe_path: &Path) -> bool {
162    let components = path_text_components(exe_path);
163    components
164        .windows(2)
165        .any(|pair| pair == ["node_modules", "@brokkai"])
166}
167
168fn path_text_components(exe_path: &Path) -> Vec<&str> {
169    exe_path
170        .components()
171        .filter_map(|component| component.as_os_str().to_str())
172        .collect()
173}
174
175fn cargo_install_root(exe_path: &Path, current_version: &str) -> Option<PathBuf> {
176    let canonical_exe = exe_path.canonicalize().ok()?;
177    let bin_dir = canonical_exe.parent()?;
178    if bin_dir.file_name()? != "bin" {
179        return None;
180    }
181    let install_root = bin_dir.parent()?;
182    cargo_install_recorded(
183        install_root,
184        "brokk-mjolnir",
185        Some(current_version),
186        BIN_NAME,
187    )
188    .then(|| install_root.to_path_buf())
189}
190
191fn cargo_install_recorded(
192    install_root: &Path,
193    package: &str,
194    version: Option<&str>,
195    binary: &str,
196) -> bool {
197    cargo_json_install_recorded(install_root, package, version, binary)
198        || cargo_toml_install_recorded(install_root, package, version, binary)
199}
200
201fn cargo_json_install_recorded(
202    install_root: &Path,
203    package: &str,
204    version: Option<&str>,
205    binary: &str,
206) -> bool {
207    let Ok(raw) = std::fs::read_to_string(install_root.join(".crates2.json")) else {
208        return false;
209    };
210    let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&raw) else {
211        return false;
212    };
213    manifest
214        .get("installs")
215        .and_then(serde_json::Value::as_object)
216        .is_some_and(|installs| {
217            installs.iter().any(|(source, record)| {
218                cargo_source_matches(source, package, version)
219                    && record
220                        .get("bins")
221                        .and_then(serde_json::Value::as_array)
222                        .is_some_and(|bins| bins.iter().any(|name| name.as_str() == Some(binary)))
223            })
224        })
225}
226
227fn cargo_toml_install_recorded(
228    install_root: &Path,
229    package: &str,
230    version: Option<&str>,
231    binary: &str,
232) -> bool {
233    let Ok(raw) = std::fs::read_to_string(install_root.join(".crates.toml")) else {
234        return false;
235    };
236    let Ok(manifest) = raw.parse::<toml::Value>() else {
237        return false;
238    };
239    manifest
240        .get("v1")
241        .and_then(toml::Value::as_table)
242        .is_some_and(|installs| {
243            installs.iter().any(|(source, bins)| {
244                cargo_source_matches(source, package, version)
245                    && bins
246                        .as_array()
247                        .is_some_and(|bins| bins.iter().any(|name| name.as_str() == Some(binary)))
248            })
249        })
250}
251
252fn cargo_source_matches(source: &str, package: &str, version: Option<&str>) -> bool {
253    let Some(rest) = source
254        .strip_prefix(package)
255        .and_then(|rest| rest.strip_prefix(' '))
256    else {
257        return false;
258    };
259    let Some(recorded_version) = rest.split_whitespace().next() else {
260        return false;
261    };
262    version.is_none_or(|expected| recorded_version == expected)
263}
264
265/// An upgrade that the running process can perform itself: the release
266/// archive and its checksum sidecar, ready to download.
267#[derive(Debug, Clone, PartialEq, Eq)]
268struct UpdateInfo {
269    version: Version,
270    tag: String,
271    asset: ReleaseAsset,
272    checksum_asset: ReleaseAsset,
273}
274
275/// What a channel reports. `Managed` upgrades delegate to the package
276/// manager; `Direct` upgrades replace the running binary from the release
277/// archive.
278#[derive(Debug, Clone, PartialEq, Eq)]
279enum AvailableUpdate {
280    Managed {
281        version: Version,
282        method: InstallMethod,
283    },
284    Direct(UpdateInfo),
285}
286
287#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
288struct GitHubRelease {
289    tag_name: String,
290    #[serde(default)]
291    assets: Vec<ReleaseAsset>,
292}
293
294#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
295struct ReleaseAsset {
296    name: String,
297    browser_download_url: String,
298}
299
300#[derive(Debug, Deserialize)]
301struct NpmLatest {
302    version: String,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq)]
306struct Platform {
307    os_family: &'static str,
308    arch: &'static str,
309    rust_target: String,
310}
311
312/// Fetches the newest release the running install's channel publishes, or
313/// `None` when the channel is not ahead of the running version.
314async fn latest_update(
315    sources: &UpdateSources,
316    method: &InstallMethod,
317) -> Result<Option<AvailableUpdate>> {
318    let current = parse_version(env!("CARGO_PKG_VERSION"))
319        .with_context(|| format!("parse current version {}", env!("CARGO_PKG_VERSION")))?;
320    if *method == InstallMethod::Direct {
321        let release = fetch_latest_release(sources)
322            .await
323            .context("fetch latest mj release")?;
324        return update_info_from_release(&release, &current, &current_platform()?)
325            .map(|update| update.map(AvailableUpdate::Direct));
326    }
327
328    let latest = fetch_latest_managed_version(sources, method).await?;
329    Ok((latest > current).then(|| AvailableUpdate::Managed {
330        version: latest,
331        method: method.clone(),
332    }))
333}
334
335async fn fetch_latest_release(sources: &UpdateSources) -> Result<GitHubRelease> {
336    let body = fetch_text(&sources.latest_release).await?;
337    serde_json::from_str(&body).context("parse release body")
338}
339
340async fn fetch_latest_managed_version(
341    sources: &UpdateSources,
342    method: &InstallMethod,
343) -> Result<Version> {
344    match method {
345        InstallMethod::Npm | InstallMethod::Npx => {
346            let body = fetch_text(&sources.npm_latest)
347                .await
348                .context("fetch latest npm package")?;
349            let latest: NpmLatest = serde_json::from_str(&body).context("parse npm metadata")?;
350            parse_version(&latest.version).context("parse latest npm version")
351        }
352        InstallMethod::Homebrew => {
353            let body = fetch_text(&sources.homebrew_formula)
354                .await
355                .context("fetch Homebrew formula")?;
356            parse_homebrew_formula_version(&body)
357        }
358        InstallMethod::Cargo { .. } => {
359            // crates.io installs are notice-only, but the notice still needs
360            // to know whether anything newer exists. The sparse index lists
361            // every published version, yanked ones included-and-skipped.
362            let body = fetch_text(&sources.cargo_index)
363                .await
364                .context("fetch crates.io index entry")?;
365            parse_cargo_index_version(&body)
366        }
367        InstallMethod::Direct => anyhow::bail!("direct installs use GitHub release metadata"),
368    }
369}
370
371const CARGO_INDEX_URL: &str = "https://index.crates.io/br/ok/brokk-mjolnir";
372
373async fn fetch_text(url: &str) -> Result<String> {
374    let client = reqwest::Client::builder()
375        .timeout(Duration::from_secs(5))
376        .user_agent(concat!("mj/", env!("CARGO_PKG_VERSION")))
377        .build()
378        .context("build http client")?;
379    let resp = client
380        .get(url)
381        .send()
382        .await
383        .with_context(|| format!("GET {url}"))?;
384    let status = resp.status();
385    if !status.is_success() {
386        anyhow::bail!("GET {url}: HTTP {status}");
387    }
388    resp.text().await.with_context(|| format!("read {url}"))
389}
390
391fn parse_homebrew_formula_version(formula: &str) -> Result<Version> {
392    let raw = formula
393        .lines()
394        .map(str::trim)
395        .find_map(|line| line.strip_prefix("version \"")?.strip_suffix('"'))
396        .ok_or_else(|| anyhow::anyhow!("Homebrew formula has no version"))?;
397    parse_version(raw).context("parse Homebrew formula version")
398}
399
400fn parse_cargo_index_version(index: &str) -> Result<Version> {
401    let mut latest: Option<Version> = None;
402    for line in index.lines().filter(|line| !line.trim().is_empty()) {
403        let entry: CargoIndexEntry =
404            serde_json::from_str(line).context("parse crates.io index entry")?;
405        if entry.yanked {
406            continue;
407        }
408        let version = parse_version(&entry.vers).context("parse crates.io package version")?;
409        if latest.as_ref().is_none_or(|current| version > *current) {
410            latest = Some(version);
411        }
412    }
413    latest.ok_or_else(|| anyhow::anyhow!("crates.io index has no published versions"))
414}
415
416#[derive(Debug, Deserialize)]
417struct CargoIndexEntry {
418    vers: String,
419    #[serde(default)]
420    yanked: bool,
421}
422
423fn update_info_from_release(
424    release: &GitHubRelease,
425    current: &Version,
426    platform: &Platform,
427) -> Result<Option<UpdateInfo>> {
428    let latest = parse_version(&release.tag_name)
429        .with_context(|| format!("parse release tag {}", release.tag_name))?;
430    if latest <= *current {
431        return Ok(None);
432    }
433
434    let asset = select_mj_asset(&release.assets, platform)
435        .with_context(|| format!("find mj asset for {}/{}", platform.os_family, platform.arch))?;
436    let checksum_name = format!("{}.sha256", asset.name);
437    let checksum_asset = release
438        .assets
439        .iter()
440        .find(|candidate| candidate.name == checksum_name)
441        .cloned()
442        .ok_or_else(|| {
443            anyhow::anyhow!(
444                "release {} is missing required checksum asset {}",
445                release.tag_name,
446                checksum_name
447            )
448        })?;
449
450    Ok(Some(UpdateInfo {
451        version: latest,
452        tag: release.tag_name.clone(),
453        asset,
454        checksum_asset,
455    }))
456}
457
458fn select_mj_asset(assets: &[ReleaseAsset], platform: &Platform) -> Result<ReleaseAsset> {
459    let target_suffix = format!(
460        "-{}{}",
461        platform.rust_target,
462        platform_archive_ext(platform)
463    );
464    if platform.os_family == "macos"
465        && let Some(asset) = assets.iter().find(|asset| {
466            is_mj_archive(&asset.name) && asset.name.ends_with("-universal-apple-darwin.tar.gz")
467        })
468    {
469        return Ok(asset.clone());
470    }
471    assets
472        .iter()
473        .find(|asset| is_mj_archive(&asset.name) && asset.name.ends_with(&target_suffix))
474        .cloned()
475        .ok_or_else(|| {
476            anyhow::anyhow!(
477                "no mj archive found for target {}; available assets: {}",
478                platform.rust_target,
479                assets
480                    .iter()
481                    .filter(|asset| !asset.name.ends_with(".sha256"))
482                    .map(|asset| asset.name.as_str())
483                    .collect::<Vec<_>>()
484                    .join(", ")
485            )
486        })
487}
488
489fn is_mj_archive(name: &str) -> bool {
490    name.starts_with("brokk-mjolnir-") && (name.ends_with(".tar.gz") || name.ends_with(".zip"))
491}
492
493fn platform_archive_ext(platform: &Platform) -> &'static str {
494    if platform.os_family == "windows" {
495        ".zip"
496    } else {
497        ".tar.gz"
498    }
499}
500
501fn current_platform() -> Result<Platform> {
502    let arch = match std::env::consts::ARCH {
503        "x86_64" => "x86_64",
504        "aarch64" | "arm64" => "aarch64",
505        other => anyhow::bail!("unsupported CPU architecture: {other}"),
506    };
507    let (os_family, rust_os) = match std::env::consts::OS {
508        "android" => ("android", "linux-android"),
509        "macos" => ("macos", "apple-darwin"),
510        "linux" => ("linux", "unknown-linux-gnu"),
511        "windows" => ("windows", "pc-windows-msvc"),
512        other => anyhow::bail!("unsupported OS: {other}"),
513    };
514
515    Ok(Platform {
516        os_family,
517        arch,
518        rust_target: format!("{arch}-{rust_os}"),
519    })
520}
521
522fn parse_version(raw: &str) -> Result<Version> {
523    Version::parse(raw.trim_start_matches('v')).with_context(|| format!("parse version {raw}"))
524}
525
526/// What the startup check decided. A successful upgrade never produces a
527/// value: the process re-execs into the new binary.
528#[derive(Debug, Clone, PartialEq, Eq)]
529pub enum StartupUpdateOutcome {
530    /// The check did not run (debug build, non-interactive, disabled, or it
531    /// failed without affecting the session).
532    Skipped,
533    UpToDate,
534    /// The channel only allows announcing the upgrade command; the user must
535    /// run it themselves.
536    Notified,
537    Declined,
538}
539
540/// Checks the running install's channel for a newer release, asks before
541/// changing anything, and on consent performs the upgrade:
542///
543/// - npm installs run `npm install -g @brokkai/mjolnir@latest` and Homebrew
544///   installs run `brew update` followed by `brew upgrade mjolnir`; mj never
545///   writes into `node_modules` or the Cellar itself, because those trees
546///   belong to the package managers.
547/// - curl installs download the release archive, verify its SHA-256 sidecar,
548///   update the controller and every bundled application helper, and re-exec.
549/// - npx and cargo installs are notice-only.
550///
551/// Runs on every interactive startup before the daemon or dashboard starts.
552/// The version fetch is time-boxed, and interactive package-manager runs share
553/// the terminal like any foreground command, so this must never be called
554/// from a UI render path.
555pub async fn check_prompt_and_apply() -> StartupUpdateOutcome {
556    // The controller ships for Linux and macOS (Windows users run WSL2), so
557    // there is no Windows replacer to maintain; debug builds are developers,
558    // who upgrade themselves.
559    if cfg!(windows)
560        || cfg!(debug_assertions)
561        || !io::stdin().is_terminal()
562        || !io::stdout().is_terminal()
563        || std::env::var_os(NO_UPDATE_CHECK_ENV).is_some()
564    {
565        return StartupUpdateOutcome::Skipped;
566    }
567
568    let method = InstallMethod::current();
569
570    let update = match latest_update(&UpdateSources::default(), &method).await {
571        Ok(Some(update)) => update,
572        Ok(None) => return StartupUpdateOutcome::UpToDate,
573        Err(error) => {
574            // A broken check must never keep someone out of mj.
575            eprintln!("mj: update check failed: {error:#}");
576            return StartupUpdateOutcome::Skipped;
577        }
578    };
579
580    match update {
581        AvailableUpdate::Direct(update) => {
582            if !prompt_for_update(&update.version, &InstallMethod::Direct).unwrap_or(false) {
583                return StartupUpdateOutcome::Declined;
584            }
585            if let Err(error) = download_apply_and_restart(&update).await {
586                eprintln!("mj: upgrade failed: {error:#}");
587                eprintln!("mj: continuing with {}", env!("CARGO_PKG_VERSION"));
588            }
589            // The success path re-execs and never returns; reaching this
590            // line means the upgrade failed and the current process lives on.
591            StartupUpdateOutcome::Skipped
592        }
593        AvailableUpdate::Managed { version, method } => match method {
594            InstallMethod::Npm | InstallMethod::Homebrew => {
595                if !prompt_for_update(&version, &method).unwrap_or(false) {
596                    return StartupUpdateOutcome::Declined;
597                }
598                let upgraded =
599                    run_managed_upgrade(&version, &method).and_then(restart_current_process);
600                if let Err(error) = upgraded {
601                    eprintln!("mj: upgrade failed: {error:#}");
602                    eprintln!("mj: continuing with {}", env!("CARGO_PKG_VERSION"));
603                }
604                StartupUpdateOutcome::Skipped
605            }
606            InstallMethod::Npx | InstallMethod::Cargo { .. } => {
607                let notice = managed_update_notice(&version, &method, env!("CARGO_PKG_VERSION"))
608                    .expect("notice-only channels have an update command");
609                println!("{notice}");
610                StartupUpdateOutcome::Notified
611            }
612            InstallMethod::Direct => {
613                unreachable!("direct installs never report managed updates")
614            }
615        },
616    }
617}
618
619fn prompt_for_update(version: &Version, method: &InstallMethod) -> Result<bool> {
620    print!(
621        "mj {version} is available through {}; current version is {}. Upgrade now? [Y/n] ",
622        method.channel_name(),
623        env!("CARGO_PKG_VERSION")
624    );
625    io::stdout().flush().context("flush update prompt")?;
626
627    read_update_answer(&mut io::stdin().lock())
628}
629
630fn read_update_answer(input: &mut impl BufRead) -> Result<bool> {
631    let mut answer = String::new();
632    let bytes_read = input
633        .read_line(&mut answer)
634        .context("read update prompt answer")?;
635    Ok(bytes_read != 0 && prompt_answer_is_yes(&answer))
636}
637
638/// An empty answer accepts, matching the 1.x prompt's default.
639fn prompt_answer_is_yes(answer: &str) -> bool {
640    matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES")
641}
642
643fn managed_update_notice(
644    version: &Version,
645    method: &InstallMethod,
646    current_version: &str,
647) -> Option<String> {
648    Some(format!(
649        "mj {version} is available through {}; current version is {current_version}. Run: {}",
650        method.channel_name(),
651        method.update_command()?
652    ))
653}
654
655fn npm_upgrade_command() -> Command {
656    let mut command = Command::new("npm");
657    command.args(["install", "-g", "@brokkai/mjolnir@latest"]);
658    command
659}
660
661fn brew_update_command() -> Command {
662    let mut command = Command::new("brew");
663    command.arg("update");
664    command
665}
666
667fn brew_upgrade_command() -> Command {
668    let mut command = Command::new("brew");
669    command.args(["upgrade", "mjolnir"]);
670    command
671}
672
673/// Runs the channel's own upgrade command in the foreground with its live
674/// output on the terminal. `run_inherited` keeps stdin closed so neither
675/// package manager can stop to ask a question nobody is there to answer.
676fn run_managed_upgrade(version: &Version, method: &InstallMethod) -> Result<RestartTarget> {
677    // npm moves and unlinks the old package. Resolve this before the upgrade,
678    // while current_exe still identifies the installation's stable path.
679    let current_exe = std::env::current_exe().context("resolve current executable")?;
680    let restart = managed_restart_target(method, &current_exe)?;
681    match method {
682        InstallMethod::Npm => {
683            println!("mj: running npm install -g @brokkai/mjolnir@latest");
684            let status = mj_core::subprocess::run_inherited(&mut npm_upgrade_command())
685                .context("run npm install -g @brokkai/mjolnir@latest")?;
686            ensure!(
687                status.success(),
688                "npm install exited with {status}; npm usually explains why above"
689            );
690        }
691        InstallMethod::Homebrew => {
692            // The version check read the tap formula on GitHub, but the
693            // local brew only knows about it after its index refreshes;
694            // without `brew update` the upgrade would report "already
695            // up-to-date" on a fresh release.
696            println!("mj: running brew update");
697            let status = mj_core::subprocess::run_inherited(&mut brew_update_command())
698                .context("run brew update")?;
699            ensure!(status.success(), "brew update exited with {status}");
700            println!("mj: running brew upgrade mjolnir");
701            let status = mj_core::subprocess::run_inherited(&mut brew_upgrade_command())
702                .context("run brew upgrade mjolnir")?;
703            ensure!(status.success(), "brew upgrade exited with {status}");
704        }
705        other => bail!("{other:?} installs do not support delegated upgrades"),
706    }
707    println!("mj: upgraded to {version}; restarting");
708    Ok(restart)
709}
710
711/// How the process re-execs after a successful managed upgrade.
712#[derive(Debug, Clone, PartialEq, Eq)]
713enum RestartTarget {
714    /// The upgrade replaced the binary file at this exact path, so re-execing
715    /// it loads the new version (direct replacements and npm bundles, whose
716    /// paths survive `npm install -g`).
717    SameExe(PathBuf),
718    /// Homebrew moves the new release into a fresh Cellar directory and
719    /// repoints its wrappers, so re-execing this process's own Cellar path
720    /// would relaunch the old version. Resolving `mj` on `PATH` runs the
721    /// formula's wrapper, which execs the new libexec binary.
722    Wrapper,
723}
724
725fn managed_restart_target(method: &InstallMethod, current_exe: &Path) -> Result<RestartTarget> {
726    match method {
727        InstallMethod::Npm => Ok(RestartTarget::SameExe(current_exe.to_path_buf())),
728        InstallMethod::Homebrew => Ok(RestartTarget::Wrapper),
729        other => bail!("{other:?} installs do not support delegated upgrades"),
730    }
731}
732
733#[cfg(unix)]
734fn restart_current_process(target: RestartTarget) -> Result<()> {
735    use std::os::unix::process::CommandExt;
736
737    let args: Vec<OsString> = std::env::args_os().skip(1).collect();
738    let mut command = match target {
739        RestartTarget::SameExe(exe) => Command::new(exe),
740        RestartTarget::Wrapper => Command::new("mj"),
741    };
742    let error = command.args(args).exec();
743    Err(error).context("exec replacement mj")
744}
745
746#[cfg(not(unix))]
747fn restart_current_process(_target: RestartTarget) -> Result<()> {
748    bail!("automatic restart is only supported on Unix platforms")
749}
750
751async fn download_apply_and_restart(update: &UpdateInfo) -> Result<()> {
752    println!("mj: downloading {} ({})", update.tag, update.asset.name);
753    let archive = download_bytes(&update.asset.browser_download_url)
754        .await
755        .with_context(|| format!("download {}", update.asset.name))?;
756    verify_checksum(update, &archive).await?;
757
758    let current_exe = std::env::current_exe().context("resolve current executable")?;
759    let replacement = install_release_archive(&current_exe, &update.asset.name, &archive)
760        .context("install release bundle")?;
761
762    println!("mj: upgraded to {}; restarting", update.tag);
763    restart_current_process(RestartTarget::SameExe(replacement))
764}
765
766async fn download_bytes(url: &str) -> Result<Vec<u8>> {
767    let client = reqwest::Client::builder()
768        .timeout(Duration::from_secs(120))
769        .user_agent(concat!("mj/", env!("CARGO_PKG_VERSION")))
770        .build()
771        .context("build http client")?;
772    let resp = client
773        .get(url)
774        .send()
775        .await
776        .with_context(|| format!("GET {url}"))?;
777    let status = resp.status();
778    if !status.is_success() {
779        anyhow::bail!("GET {url}: HTTP {status}");
780    }
781    resp.bytes()
782        .await
783        .map(|bytes| bytes.to_vec())
784        .context("read response body")
785}
786
787async fn verify_checksum(update: &UpdateInfo, archive: &[u8]) -> Result<()> {
788    let body = download_bytes(&update.checksum_asset.browser_download_url)
789        .await
790        .with_context(|| format!("download {}", update.checksum_asset.name))?;
791    let body = String::from_utf8(body).context("checksum file is not utf-8")?;
792    let expected = body
793        .split_whitespace()
794        .next()
795        .ok_or_else(|| anyhow::anyhow!("empty checksum file {}", update.checksum_asset.name))?;
796    let actual = sha256_hex(archive);
797    if expected != actual {
798        bail!(
799            "checksum mismatch for {}: expected {expected}, got {actual}",
800            update.asset.name
801        );
802    }
803    Ok(())
804}
805
806fn sha256_hex(bytes: &[u8]) -> String {
807    let mut hasher = Sha256::new();
808    hasher.update(bytes);
809    lower_hex(hasher.finalize())
810}
811
812/// Extract the complete application bundle before changing any installed file.
813/// Companions can be retired in future releases, but mj itself is mandatory.
814fn install_release_archive(
815    current_exe: &Path,
816    archive_name: &str,
817    archive_bytes: &[u8],
818) -> Result<PathBuf> {
819    ensure!(
820        cfg!(unix),
821        "self-update replacement is only supported on Unix platforms"
822    );
823    let target_exe = current_exe
824        .canonicalize()
825        .with_context(|| format!("resolve executable target {}", current_exe.display()))?;
826    let parent = target_exe
827        .parent()
828        .ok_or_else(|| anyhow::anyhow!("executable has no parent: {}", target_exe.display()))?;
829    // Keep staging on the destination filesystem so each replacement is an
830    // atomic rename, including binaries that are currently running.
831    let staging = tempfile::Builder::new()
832        .prefix(".mj-self-update-")
833        .tempdir_in(parent)
834        .context("create update staging directory")?;
835    let mut binaries = stage_release_archive(archive_name, archive_bytes, staging.path())?;
836    let executable_name = if archive_name.ends_with(".zip") {
837        WINDOWS_BIN_NAME
838    } else {
839        BIN_NAME
840    };
841    ensure!(
842        staging.path().join(executable_name).is_file(),
843        "archive did not contain expected binary: {executable_name}"
844    );
845    // Replace the controller last, once every packaged companion is installed.
846    binaries.sort_by_key(|path| path.file_name() == Some(executable_name.as_ref()));
847    strip_quarantine(staging.path());
848    for binary in binaries {
849        let name = binary
850            .file_name()
851            .context("staged binary has no file name")?;
852        let target = if name == executable_name {
853            target_exe.clone()
854        } else {
855            parent.join(name)
856        };
857        std::fs::rename(&binary, &target)
858            .with_context(|| format!("install {}", target.display()))?;
859    }
860    Ok(target_exe)
861}
862
863fn stage_release_archive(
864    archive_name: &str,
865    archive_bytes: &[u8],
866    directory: &Path,
867) -> Result<Vec<PathBuf>> {
868    let mut binaries = Vec::new();
869    if archive_name.ends_with(".zip") {
870        let mut archive =
871            zip::ZipArchive::new(Cursor::new(archive_bytes)).context("open zip archive")?;
872        for index in 0..archive.len() {
873            let mut entry = archive.by_index(index).context("read zip entry")?;
874            let path = entry.enclosed_name().ok_or_else(|| {
875                anyhow::anyhow!("zip entry escapes destination: {}", entry.name())
876            })?;
877            let is_file = entry.is_file() && !entry.is_symlink();
878            if let Some(binary) = stage_archive_binary(directory, &path, is_file, &mut entry)? {
879                binaries.push(binary);
880            }
881        }
882    } else {
883        let mut archive = tar::Archive::new(GzDecoder::new(archive_bytes));
884        for entry in archive.entries().context("read tar entries")? {
885            let mut entry = entry.context("read tar entry")?;
886            let path = entry.path().context("read tar entry path")?.into_owned();
887            let is_file = entry.header().entry_type().is_file();
888            if let Some(binary) = stage_archive_binary(directory, &path, is_file, &mut entry)? {
889                binaries.push(binary);
890            }
891        }
892    }
893    Ok(binaries)
894}
895
896fn stage_archive_binary(
897    directory: &Path,
898    path: &Path,
899    is_file: bool,
900    mut contents: impl Read,
901) -> Result<Option<PathBuf>> {
902    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
903        return Ok(None);
904    };
905    let stem = name.strip_suffix(".exe").unwrap_or(name);
906    if !matches!(
907        stem,
908        BIN_NAME | "mj-desktop" | VOICE_WORKER_NAME | "mj-worker"
909    ) && !stem.starts_with("mj-worker-")
910    {
911        return Ok(None);
912    }
913    ensure!(
914        is_file,
915        "archive binary is not a regular file: {}",
916        path.display()
917    );
918    let target = directory.join(name);
919    let mut output = std::fs::File::create_new(&target)
920        .with_context(|| format!("stage {name}; each binary must appear only once"))?;
921    let size = io::copy(&mut contents, &mut output).with_context(|| format!("extract {name}"))?;
922    ensure!(size != 0, "archive contained an empty {name} binary");
923    #[cfg(unix)]
924    {
925        use std::os::unix::fs::PermissionsExt;
926        output
927            .set_permissions(std::fs::Permissions::from_mode(0o755))
928            .with_context(|| format!("chmod {name}"))?;
929    }
930    Ok(Some(target))
931}
932
933#[cfg(unix)]
934fn strip_quarantine(path: &Path) {
935    #[cfg(target_os = "macos")]
936    {
937        // Downloads inherit a quarantine attribute on macOS; Gatekeeper
938        // would refuse to exec the replacement without this.
939        let _ = Command::new("xattr")
940            .arg("-dr")
941            .arg("com.apple.quarantine")
942            .arg(path)
943            .status();
944    }
945    #[cfg(not(target_os = "macos"))]
946    {
947        let _ = path;
948    }
949}
950
951#[cfg(not(unix))]
952fn strip_quarantine(_path: &Path) {}
953
954#[cfg(test)]
955mod tests;