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 --formula brokkai/tap/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    assets
465        .iter()
466        .find(|asset| is_mj_archive(&asset.name) && asset.name.ends_with(&target_suffix))
467        .cloned()
468        .ok_or_else(|| {
469            anyhow::anyhow!(
470                "no mj archive found for target {}; available assets: {}",
471                platform.rust_target,
472                assets
473                    .iter()
474                    .filter(|asset| !asset.name.ends_with(".sha256"))
475                    .map(|asset| asset.name.as_str())
476                    .collect::<Vec<_>>()
477                    .join(", ")
478            )
479        })
480}
481
482fn is_mj_archive(name: &str) -> bool {
483    name.starts_with("brokk-mjolnir-") && (name.ends_with(".tar.gz") || name.ends_with(".zip"))
484}
485
486fn platform_archive_ext(platform: &Platform) -> &'static str {
487    if platform.os_family == "windows" {
488        ".zip"
489    } else {
490        ".tar.gz"
491    }
492}
493
494fn current_platform() -> Result<Platform> {
495    let arch = match std::env::consts::ARCH {
496        "x86_64" => "x86_64",
497        "aarch64" | "arm64" => "aarch64",
498        other => anyhow::bail!("unsupported CPU architecture: {other}"),
499    };
500    let (os_family, rust_os) = match std::env::consts::OS {
501        "android" => ("android", "linux-android"),
502        "macos" => ("macos", "apple-darwin"),
503        "linux" => ("linux", "unknown-linux-gnu"),
504        "windows" => ("windows", "pc-windows-msvc"),
505        other => anyhow::bail!("unsupported OS: {other}"),
506    };
507
508    Ok(Platform {
509        os_family,
510        arch,
511        rust_target: format!("{arch}-{rust_os}"),
512    })
513}
514
515fn parse_version(raw: &str) -> Result<Version> {
516    Version::parse(raw.trim_start_matches('v')).with_context(|| format!("parse version {raw}"))
517}
518
519/// What the startup check decided. A successful upgrade never produces a
520/// value: the process re-execs into the new binary.
521#[derive(Debug, Clone, PartialEq, Eq)]
522pub enum StartupUpdateOutcome {
523    /// The check did not run (debug build, non-interactive, disabled, or it
524    /// failed without affecting the session).
525    Skipped,
526    UpToDate,
527    /// The channel only allows announcing the upgrade command; the user must
528    /// run it themselves.
529    Notified,
530    Declined,
531}
532
533/// Checks the running install's channel for a newer release, asks before
534/// changing anything, and on consent performs the upgrade:
535///
536/// - npm installs run `npm install -g @brokkai/mjolnir@latest` and Homebrew
537///   installs run `brew update` followed by
538///   `brew upgrade --formula brokkai/tap/mjolnir`; mj never writes into
539///   `node_modules` or the Cellar itself, because those trees belong to the
540///   package managers.
541/// - curl installs download the release archive, verify its SHA-256 sidecar,
542///   update the controller and every bundled application helper, and re-exec.
543/// - npx and cargo installs are notice-only.
544///
545/// Runs on every interactive startup before the daemon or dashboard starts.
546/// The version fetch is time-boxed, and interactive package-manager runs share
547/// the terminal like any foreground command, so this must never be called
548/// from a UI render path.
549pub async fn check_prompt_and_apply() -> StartupUpdateOutcome {
550    // The controller ships for Linux and macOS (Windows users run WSL2), so
551    // there is no Windows replacer to maintain; debug builds are developers,
552    // who upgrade themselves.
553    if cfg!(windows)
554        || cfg!(debug_assertions)
555        || !io::stdin().is_terminal()
556        || !io::stdout().is_terminal()
557        || std::env::var_os(NO_UPDATE_CHECK_ENV).is_some()
558    {
559        return StartupUpdateOutcome::Skipped;
560    }
561
562    let method = InstallMethod::current();
563
564    let update = match latest_update(&UpdateSources::default(), &method).await {
565        Ok(Some(update)) => update,
566        Ok(None) => return StartupUpdateOutcome::UpToDate,
567        Err(error) => {
568            // A broken check must never keep someone out of mj.
569            eprintln!("mj: update check failed: {error:#}");
570            return StartupUpdateOutcome::Skipped;
571        }
572    };
573
574    match update {
575        AvailableUpdate::Direct(update) => {
576            if !prompt_for_update(&update.version, &InstallMethod::Direct).unwrap_or(false) {
577                return StartupUpdateOutcome::Declined;
578            }
579            if let Err(error) = download_apply_and_restart(&update).await {
580                eprintln!("mj: upgrade failed: {error:#}");
581                eprintln!("mj: continuing with {}", env!("CARGO_PKG_VERSION"));
582            }
583            // The success path re-execs and never returns; reaching this
584            // line means the upgrade failed and the current process lives on.
585            StartupUpdateOutcome::Skipped
586        }
587        AvailableUpdate::Managed { version, method } => match method {
588            InstallMethod::Npm | InstallMethod::Homebrew => {
589                if !prompt_for_update(&version, &method).unwrap_or(false) {
590                    return StartupUpdateOutcome::Declined;
591                }
592                let upgraded =
593                    run_managed_upgrade(&version, &method).and_then(restart_current_process);
594                if let Err(error) = upgraded {
595                    eprintln!("mj: upgrade failed: {error:#}");
596                    eprintln!("mj: continuing with {}", env!("CARGO_PKG_VERSION"));
597                }
598                StartupUpdateOutcome::Skipped
599            }
600            InstallMethod::Npx | InstallMethod::Cargo { .. } => {
601                let notice = managed_update_notice(&version, &method, env!("CARGO_PKG_VERSION"))
602                    .expect("notice-only channels have an update command");
603                println!("{notice}");
604                StartupUpdateOutcome::Notified
605            }
606            InstallMethod::Direct => {
607                unreachable!("direct installs never report managed updates")
608            }
609        },
610    }
611}
612
613fn prompt_for_update(version: &Version, method: &InstallMethod) -> Result<bool> {
614    print!(
615        "mj {version} is available through {}; current version is {}. Upgrade now? [Y/n] ",
616        method.channel_name(),
617        env!("CARGO_PKG_VERSION")
618    );
619    io::stdout().flush().context("flush update prompt")?;
620
621    read_update_answer(&mut io::stdin().lock())
622}
623
624fn read_update_answer(input: &mut impl BufRead) -> Result<bool> {
625    let mut answer = String::new();
626    let bytes_read = input
627        .read_line(&mut answer)
628        .context("read update prompt answer")?;
629    Ok(bytes_read != 0 && prompt_answer_is_yes(&answer))
630}
631
632/// An empty answer accepts, matching the 1.x prompt's default.
633fn prompt_answer_is_yes(answer: &str) -> bool {
634    matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES")
635}
636
637fn managed_update_notice(
638    version: &Version,
639    method: &InstallMethod,
640    current_version: &str,
641) -> Option<String> {
642    Some(format!(
643        "mj {version} is available through {}; current version is {current_version}. Run: {}",
644        method.channel_name(),
645        method.update_command()?
646    ))
647}
648
649fn npm_upgrade_command() -> Command {
650    let mut command = Command::new("npm");
651    command.args(["install", "-g", "@brokkai/mjolnir@latest"]);
652    command
653}
654
655fn brew_update_command() -> Command {
656    let mut command = Command::new("brew");
657    command.arg("update");
658    command
659}
660
661fn brew_upgrade_command() -> Command {
662    let mut command = Command::new("brew");
663    // A bare `mjolnir` resolves to an unrelated Homebrew cask, so name the
664    // tap formula explicitly.
665    command.args(["upgrade", "--formula", "brokkai/tap/mjolnir"]);
666    command
667}
668
669/// Runs the channel's own upgrade command in the foreground with its live
670/// output on the terminal. `run_inherited` keeps stdin closed so neither
671/// package manager can stop to ask a question nobody is there to answer.
672fn run_managed_upgrade(version: &Version, method: &InstallMethod) -> Result<RestartTarget> {
673    // npm moves and unlinks the old package. Resolve this before the upgrade,
674    // while current_exe still identifies the installation's stable path.
675    let current_exe = std::env::current_exe().context("resolve current executable")?;
676    let restart = managed_restart_target(method, &current_exe)?;
677    match method {
678        InstallMethod::Npm => {
679            println!("mj: running npm install -g @brokkai/mjolnir@latest");
680            let status = mj_core::subprocess::run_inherited(&mut npm_upgrade_command())
681                .context("run npm install -g @brokkai/mjolnir@latest")?;
682            ensure!(
683                status.success(),
684                "npm install exited with {status}; npm usually explains why above"
685            );
686        }
687        InstallMethod::Homebrew => {
688            // The version check read the tap formula on GitHub, but the
689            // local brew only knows about it after its index refreshes;
690            // without `brew update` the upgrade would report "already
691            // up-to-date" on a fresh release.
692            println!("mj: running brew update");
693            let status = mj_core::subprocess::run_inherited(&mut brew_update_command())
694                .context("run brew update")?;
695            ensure!(status.success(), "brew update exited with {status}");
696            println!("mj: running brew upgrade --formula brokkai/tap/mjolnir");
697            let status = mj_core::subprocess::run_inherited(&mut brew_upgrade_command())
698                .context("run brew upgrade --formula brokkai/tap/mjolnir")?;
699            ensure!(status.success(), "brew upgrade exited with {status}");
700        }
701        other => bail!("{other:?} installs do not support delegated upgrades"),
702    }
703    println!("mj: upgraded to {version}; restarting");
704    Ok(restart)
705}
706
707/// How the process re-execs after a successful managed upgrade.
708#[derive(Debug, Clone, PartialEq, Eq)]
709enum RestartTarget {
710    /// The upgrade replaced the binary file at this exact path, so re-execing
711    /// it loads the new version (direct replacements and npm bundles, whose
712    /// paths survive `npm install -g`).
713    SameExe(PathBuf),
714    /// Homebrew moves the new release into a fresh Cellar directory and
715    /// repoints its wrappers, so re-execing this process's own Cellar path
716    /// would relaunch the old version. Resolving `mj` on `PATH` runs the
717    /// formula's wrapper, which execs the new libexec binary.
718    Wrapper,
719}
720
721fn managed_restart_target(method: &InstallMethod, current_exe: &Path) -> Result<RestartTarget> {
722    match method {
723        InstallMethod::Npm => Ok(RestartTarget::SameExe(current_exe.to_path_buf())),
724        InstallMethod::Homebrew => Ok(RestartTarget::Wrapper),
725        other => bail!("{other:?} installs do not support delegated upgrades"),
726    }
727}
728
729#[cfg(unix)]
730fn restart_current_process(target: RestartTarget) -> Result<()> {
731    use std::os::unix::process::CommandExt;
732
733    let args: Vec<OsString> = std::env::args_os().skip(1).collect();
734    let mut command = match target {
735        RestartTarget::SameExe(exe) => Command::new(exe),
736        RestartTarget::Wrapper => Command::new("mj"),
737    };
738    let error = command.args(args).exec();
739    Err(error).context("exec replacement mj")
740}
741
742#[cfg(not(unix))]
743fn restart_current_process(_target: RestartTarget) -> Result<()> {
744    bail!("automatic restart is only supported on Unix platforms")
745}
746
747async fn download_apply_and_restart(update: &UpdateInfo) -> Result<()> {
748    println!("mj: downloading {} ({})", update.tag, update.asset.name);
749    let archive = download_bytes(&update.asset.browser_download_url)
750        .await
751        .with_context(|| format!("download {}", update.asset.name))?;
752    verify_checksum(update, &archive).await?;
753
754    let current_exe = std::env::current_exe().context("resolve current executable")?;
755    let replacement = install_release_archive(&current_exe, &update.asset.name, &archive)
756        .context("install release bundle")?;
757
758    println!("mj: upgraded to {}; restarting", update.tag);
759    restart_current_process(RestartTarget::SameExe(replacement))
760}
761
762async fn download_bytes(url: &str) -> Result<Vec<u8>> {
763    let client = reqwest::Client::builder()
764        .timeout(Duration::from_secs(120))
765        .user_agent(concat!("mj/", env!("CARGO_PKG_VERSION")))
766        .build()
767        .context("build http client")?;
768    let resp = client
769        .get(url)
770        .send()
771        .await
772        .with_context(|| format!("GET {url}"))?;
773    let status = resp.status();
774    if !status.is_success() {
775        anyhow::bail!("GET {url}: HTTP {status}");
776    }
777    resp.bytes()
778        .await
779        .map(|bytes| bytes.to_vec())
780        .context("read response body")
781}
782
783async fn verify_checksum(update: &UpdateInfo, archive: &[u8]) -> Result<()> {
784    let body = download_bytes(&update.checksum_asset.browser_download_url)
785        .await
786        .with_context(|| format!("download {}", update.checksum_asset.name))?;
787    let body = String::from_utf8(body).context("checksum file is not utf-8")?;
788    let expected = body
789        .split_whitespace()
790        .next()
791        .ok_or_else(|| anyhow::anyhow!("empty checksum file {}", update.checksum_asset.name))?;
792    let actual = sha256_hex(archive);
793    if expected != actual {
794        bail!(
795            "checksum mismatch for {}: expected {expected}, got {actual}",
796            update.asset.name
797        );
798    }
799    Ok(())
800}
801
802fn sha256_hex(bytes: &[u8]) -> String {
803    let mut hasher = Sha256::new();
804    hasher.update(bytes);
805    lower_hex(hasher.finalize())
806}
807
808/// Extract the complete application bundle before changing any installed file.
809/// Companions can be retired in future releases, but mj itself is mandatory.
810fn install_release_archive(
811    current_exe: &Path,
812    archive_name: &str,
813    archive_bytes: &[u8],
814) -> Result<PathBuf> {
815    ensure!(
816        cfg!(unix),
817        "self-update replacement is only supported on Unix platforms"
818    );
819    let target_exe = current_exe
820        .canonicalize()
821        .with_context(|| format!("resolve executable target {}", current_exe.display()))?;
822    let parent = target_exe
823        .parent()
824        .ok_or_else(|| anyhow::anyhow!("executable has no parent: {}", target_exe.display()))?;
825    // Keep staging on the destination filesystem so each replacement is an
826    // atomic rename, including binaries that are currently running.
827    let staging = tempfile::Builder::new()
828        .prefix(".mj-self-update-")
829        .tempdir_in(parent)
830        .context("create update staging directory")?;
831    let mut binaries = stage_release_archive(archive_name, archive_bytes, staging.path())?;
832    let executable_name = if archive_name.ends_with(".zip") {
833        WINDOWS_BIN_NAME
834    } else {
835        BIN_NAME
836    };
837    ensure!(
838        staging.path().join(executable_name).is_file(),
839        "archive did not contain expected binary: {executable_name}"
840    );
841    // Replace the controller last, once every packaged companion is installed.
842    binaries.sort_by_key(|path| path.file_name() == Some(executable_name.as_ref()));
843    strip_quarantine(staging.path());
844    for binary in binaries {
845        let name = binary
846            .file_name()
847            .context("staged binary has no file name")?;
848        let target = if name == executable_name {
849            target_exe.clone()
850        } else {
851            parent.join(name)
852        };
853        std::fs::rename(&binary, &target)
854            .with_context(|| format!("install {}", target.display()))?;
855    }
856    Ok(target_exe)
857}
858
859fn stage_release_archive(
860    archive_name: &str,
861    archive_bytes: &[u8],
862    directory: &Path,
863) -> Result<Vec<PathBuf>> {
864    let mut binaries = Vec::new();
865    if archive_name.ends_with(".zip") {
866        let mut archive =
867            zip::ZipArchive::new(Cursor::new(archive_bytes)).context("open zip archive")?;
868        for index in 0..archive.len() {
869            let mut entry = archive.by_index(index).context("read zip entry")?;
870            let path = entry.enclosed_name().ok_or_else(|| {
871                anyhow::anyhow!("zip entry escapes destination: {}", entry.name())
872            })?;
873            let is_file = entry.is_file() && !entry.is_symlink();
874            if let Some(binary) = stage_archive_binary(directory, &path, is_file, &mut entry)? {
875                binaries.push(binary);
876            }
877        }
878    } else {
879        let mut archive = tar::Archive::new(GzDecoder::new(archive_bytes));
880        for entry in archive.entries().context("read tar entries")? {
881            let mut entry = entry.context("read tar entry")?;
882            let path = entry.path().context("read tar entry path")?.into_owned();
883            let is_file = entry.header().entry_type().is_file();
884            if let Some(binary) = stage_archive_binary(directory, &path, is_file, &mut entry)? {
885                binaries.push(binary);
886            }
887        }
888    }
889    Ok(binaries)
890}
891
892fn stage_archive_binary(
893    directory: &Path,
894    path: &Path,
895    is_file: bool,
896    mut contents: impl Read,
897) -> Result<Option<PathBuf>> {
898    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
899        return Ok(None);
900    };
901    let stem = name.strip_suffix(".exe").unwrap_or(name);
902    if !matches!(
903        stem,
904        BIN_NAME | "mj-desktop" | VOICE_WORKER_NAME | "mj-worker"
905    ) && !stem.starts_with("mj-worker-")
906    {
907        return Ok(None);
908    }
909    ensure!(
910        is_file,
911        "archive binary is not a regular file: {}",
912        path.display()
913    );
914    let target = directory.join(name);
915    let mut output = std::fs::File::create_new(&target)
916        .with_context(|| format!("stage {name}; each binary must appear only once"))?;
917    let size = io::copy(&mut contents, &mut output).with_context(|| format!("extract {name}"))?;
918    ensure!(size != 0, "archive contained an empty {name} binary");
919    #[cfg(unix)]
920    {
921        use std::os::unix::fs::PermissionsExt;
922        output
923            .set_permissions(std::fs::Permissions::from_mode(0o755))
924            .with_context(|| format!("chmod {name}"))?;
925    }
926    Ok(Some(target))
927}
928
929#[cfg(unix)]
930fn strip_quarantine(path: &Path) {
931    #[cfg(target_os = "macos")]
932    {
933        // Downloads inherit a quarantine attribute on macOS; Gatekeeper
934        // would refuse to exec the replacement without this.
935        let _ = Command::new("xattr")
936            .arg("-dr")
937            .arg("com.apple.quarantine")
938            .arg(path)
939            .status();
940    }
941    #[cfg(not(target_os = "macos"))]
942    {
943        let _ = path;
944    }
945}
946
947#[cfg(not(unix))]
948fn strip_quarantine(_path: &Path) {}
949
950#[cfg(test)]
951mod tests;