diff --git a/crates/alkane-artifacts/src/fetch.rs b/crates/alkane-artifacts/src/fetch.rs index 3a8c4958..7eef9164 100644 --- a/crates/alkane-artifacts/src/fetch.rs +++ b/crates/alkane-artifacts/src/fetch.rs @@ -48,12 +48,33 @@ pub enum FetchError { } /// Where releases come from. Defaults to the alkane-os repo on the self-hosted -/// Gitea; the base URL and token are read from the environment. +/// Gitea; a full repo URL on any Gitea or GitHub host is also accepted so an +/// operator can flash from their own fork. pub struct ReleaseSource { pub base_url: String, pub owner: String, pub repo: String, pub token: Option, + /// GitHub uses `api.github.com/repos/...` instead of a Gitea + /// `.../api/v1/repos/...` path. + pub github: bool, +} + +/// The default self-hosted Gitea base (honoring `ALKANE_RELEASE_BASE`). +fn default_gitea_base() -> String { + std::env::var("ALKANE_RELEASE_BASE") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "https://gitea.bluefla.re".to_string()) +} + +/// Resolve the token for the default self-hosted Gitea (never sent elsewhere). +fn gitea_token() -> Option { + std::env::var("ALKANE_RELEASE_TOKEN") + .ok() + .or_else(|| std::env::var("GITEA_TOKEN").ok()) + .filter(|t| !t.is_empty()) + .or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty())) } impl ReleaseSource { @@ -63,37 +84,126 @@ impl ReleaseSource { Self::for_repo("blueflare", "alkane-os") } - /// A release source for an arbitrary Gitea `owner`/`repo`. The base URL - /// (`ALKANE_RELEASE_BASE`, else the self-hosted Gitea) and the token - /// (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`, else the build-time embedded - /// token) are resolved exactly as for `alkane_os`. + /// A release source for an arbitrary Gitea `owner`/`repo` on the default + /// self-hosted Gitea base, with the resolved Gitea token. pub fn for_repo(owner: &str, repo: &str) -> Self { - let base_url = std::env::var("ALKANE_RELEASE_BASE") - .ok() - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| "https://gitea.bluefla.re".to_string()); - let token = std::env::var("ALKANE_RELEASE_TOKEN") - .ok() - .or_else(|| std::env::var("GITEA_TOKEN").ok()) - .filter(|t| !t.is_empty()) - .or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty())); Self { - base_url, + base_url: default_gitea_base(), owner: owner.to_string(), repo: repo.to_string(), + token: gitea_token(), + github: false, + } + } + + /// Parse a full repo URL (or a bare `owner/repo`) into a release source. + /// Supports any Gitea host and GitHub (`github.com`); a bare `owner/repo` + /// uses the default self-hosted Gitea. Accepts optional scheme, a trailing + /// `.git`, and trailing path noise (e.g. `/releases`). + /// + /// The resolved Gitea token is attached ONLY when the host is the default + /// self-hosted Gitea, so the embedded admin token is never sent to GitHub or + /// any other host (those use anonymous access to public releases). + pub fn from_url(input: &str) -> Option { + let s = input.trim().trim_end_matches('/'); + if s.is_empty() { + return None; + } + let no_scheme = s + .strip_prefix("https://") + .or_else(|| s.strip_prefix("http://")) + .unwrap_or(s); + let parts: Vec<&str> = no_scheme.split('/').filter(|p| !p.is_empty()).collect(); + // host present when the first segment looks like a hostname (has a dot). + let (host, owner, repo) = if parts.len() >= 3 && parts[0].contains('.') { + (Some(parts[0]), parts[1], parts[2]) + } else if parts.len() == 2 && !parts[0].contains('.') { + (None, parts[0], parts[1]) + } else { + return None; + }; + let repo = repo.trim_end_matches(".git"); + if owner.is_empty() || repo.is_empty() { + return None; + } + let default_host = default_gitea_base() + .trim_start_matches("https://") + .trim_start_matches("http://") + .trim_end_matches('/') + .to_string(); + let src = match host { + Some("github.com") | Some("www.github.com") => ReleaseSource { + base_url: "https://api.github.com".to_string(), + owner: owner.to_string(), + repo: repo.to_string(), + token: None, // never send the gitea token to github + github: true, + }, + Some(h) if h == default_host => ReleaseSource { + base_url: default_gitea_base(), + owner: owner.to_string(), + repo: repo.to_string(), + token: gitea_token(), + github: false, + }, + Some(h) => ReleaseSource { + base_url: format!("https://{h}"), + owner: owner.to_string(), + repo: repo.to_string(), + token: None, // a different Gitea host: anonymous public access + github: false, + }, + None => Self::for_repo(owner, repo), + }; + Some(src) + } + + /// A minimal source for downloading a release asset by its direct URL. The + /// gitea token is attached ONLY when the asset URL is on the trusted + /// self-hosted Gitea host; GitHub and other hosts get anonymous access, so + /// the embedded admin token is never sent off-host. + pub fn for_asset_url(url: &str) -> ReleaseSource { + let host = url + .trim_start_matches("https://") + .trim_start_matches("http://") + .split('/') + .next() + .unwrap_or(""); + let default_host = default_gitea_base() + .trim_start_matches("https://") + .trim_start_matches("http://") + .trim_end_matches('/') + .to_string(); + let token = if host == default_host { + gitea_token() + } else { + None + }; + ReleaseSource { + base_url: format!("https://{host}"), + owner: String::new(), + repo: String::new(), token, + github: host.eq_ignore_ascii_case("api.github.com") + || host.eq_ignore_ascii_case("github.com"), } } /// The releases list (newest first). Unlike `releases/latest`, this includes /// pre-releases, so an early/bench channel is still found by `--latest`. fn api_list(&self) -> String { - format!( - "{}/api/v1/repos/{}/{}/releases?limit=50", - self.base_url.trim_end_matches('/'), - self.owner, - self.repo - ) + let base = self.base_url.trim_end_matches('/'); + if self.github { + format!( + "{}/repos/{}/{}/releases?per_page=50", + base, self.owner, self.repo + ) + } else { + format!( + "{}/api/v1/repos/{}/{}/releases?limit=50", + base, self.owner, self.repo + ) + } } } @@ -174,7 +284,10 @@ fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> { fn curl_bytes(src: &ReleaseSource, url: &str) -> Result, FetchError> { let config = TokenConfig::new(&src.token)?; let mut cmd = Command::new("curl"); - cmd.arg("-fsSL").arg("--max-time").arg("120"); + // A generic User-Agent (GitHub's API rejects requests without one); never + // carries any operator/host detail. + cmd.arg("-fsSL").arg("-A").arg("alkane-toolkit"); + cmd.arg("--max-time").arg("120"); config.apply(&mut cmd); cmd.arg(url); let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?; @@ -192,6 +305,8 @@ fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), Fetc let config = TokenConfig::new(&src.token)?; let mut cmd = Command::new("curl"); cmd.arg("-fsSL") + .arg("-A") + .arg("alkane-toolkit") .arg("--max-time") .arg("600") .arg("-o") @@ -380,6 +495,54 @@ pub fn fetch_afw_url( mod tests { use super::*; + #[test] + fn from_url_parses_gitea_github_and_bare() { + std::env::remove_var("ALKANE_RELEASE_BASE"); + // Bare owner/repo -> default gitea. + let g = ReleaseSource::from_url("someone/alkane-os").unwrap(); + assert_eq!( + (g.owner.as_str(), g.repo.as_str()), + ("someone", "alkane-os") + ); + assert!( + !g.github + && g.api_list() + .contains("gitea.bluefla.re/api/v1/repos/someone/alkane-os") + ); + + // Full gitea URL on the default host keeps the token path + gitea API. + let gh = ReleaseSource::from_url("https://gitea.bluefla.re/blueflare/alkane-os").unwrap(); + assert!(!gh.github && gh.api_list().contains("/api/v1/repos/blueflare/alkane-os")); + + // GitHub URL -> api.github.com, github path, and NEVER a token. + let h = ReleaseSource::from_url("https://github.com/acme/alkane-os.git/releases").unwrap(); + assert!(h.github); + assert!( + h.token.is_none(), + "must not attach the gitea token to github" + ); + assert_eq!( + h.api_list(), + "https://api.github.com/repos/acme/alkane-os/releases?per_page=50" + ); + + // Another gitea host -> no token (not the trusted host), gitea path. + let other = ReleaseSource::from_url("https://git.example.org/u/r").unwrap(); + assert!(!other.github && other.token.is_none()); + assert!(other + .api_list() + .starts_with("https://git.example.org/api/v1/repos/u/r")); + + // Asset download token only for the trusted host. + assert!(ReleaseSource::for_asset_url( + "https://github.com/acme/r/releases/download/v1/x.afw" + ) + .token + .is_none()); + assert!(ReleaseSource::from_url("").is_none()); + assert!(ReleaseSource::from_url("justonepart").is_none()); + } + #[test] fn source_defaults_to_alkane_os_on_gitea() { std::env::remove_var("ALKANE_RELEASE_BASE"); diff --git a/crates/alkane-gui/src/alkane_detect.rs b/crates/alkane-gui/src/alkane_detect.rs index 01227c43..885f48bc 100644 --- a/crates/alkane-gui/src/alkane_detect.rs +++ b/crates/alkane-gui/src/alkane_detect.rs @@ -137,6 +137,70 @@ fn parse_http_json(raw: &[u8]) -> Option { serde_json::from_str(body.trim()).ok() } +/// Read the raw HTTP response head (status line + headers) of a GET on :80. +async fn http_response_head(ip: IpAddr, path: &str) -> Option { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let connect = tokio::net::TcpStream::connect((ip, 80)); + let mut stream = tokio::time::timeout(CONNECT_TIMEOUT, connect) + .await + .ok()? + .ok()?; + let request = format!("GET {path} HTTP/1.0\r\nHost: {ip}\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.ok()?; + let mut raw = Vec::new(); + let _ = tokio::time::timeout(READ_TIMEOUT, async { + let mut chunk = [0u8; 2048]; + loop { + match stream.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + raw.extend_from_slice(&chunk[..n]); + if raw.windows(4).any(|w| w == b"\r\n\r\n") || raw.len() > 8192 { + break; + } + } + } + } + }) + .await; + let text = String::from_utf8_lossy(&raw); + let head = text.split("\r\n\r\n").next().unwrap_or("").to_string(); + (!head.is_empty()).then_some(head) +} + +/// A stock Antminer whose miner API (:4028) is down -- e.g. no hashboards, so +/// the miner software is not running -- still serves its vendor web UI on :80 +/// with a `Digest realm="antMiner Configuration"` challenge. asic-rs cannot +/// identify such a board without the API, so recognise it here. The control +/// board/model are unknown from :80 alone, so the row is marked stock with an +/// unknown board; the operator picks the control board when flashing. +pub async fn detect_stock_antminer(ip: IpAddr) -> Option { + let head = http_response_head(ip, "/").await?; + let lower = head.to_ascii_lowercase(); + let is_stock_antminer = lower.contains("antminer configuration") + || (lower.contains("server: lighttpd") && lower.contains(" 401 ")); + if !is_stock_antminer { + return None; + } + Some(MinerRow { + ip: ip.to_string(), + brand: "Antminer".to_string(), + model: "Stock (model unknown)".to_string(), + firmware: "Stock".to_string(), + ..Default::default() + }) +} + +/// A stock Antminer the scan could identify as such but whose control board is +/// unknown (e.g. found only by its :80 vendor web UI). Alkane can still be +/// installed once the operator picks the control board, so the install flow +/// offers it with a manual board selector. +pub fn is_unidentified_stock_antminer(row: &MinerRow) -> bool { + row.brand.to_ascii_lowercase().contains("antminer") + && row.firmware.eq_ignore_ascii_case("Stock") + && board_family(row).is_none() +} + /// Whether the row is a board running Alkane OS (found by `detect`). pub fn is_alkane(row: &MinerRow) -> bool { row.alkane_board.is_some() @@ -310,6 +374,37 @@ mod tests { assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d")); } + #[test] + fn an_unidentified_stock_antminer_is_flaggable_for_manual_board_install() { + // As detect_stock_antminer builds it: brand Antminer, Stock, no control + // board (found only by its :80 web UI). + let row = MinerRow { + brand: "Antminer".into(), + model: "Stock (model unknown)".into(), + firmware: "Stock".into(), + ..Default::default() + }; + assert!(is_unidentified_stock_antminer(&row)); + assert!(board_family(&row).is_none()); + assert!(!is_alkane(&row)); + // A board with a known control board is NOT "unidentified". + let s17 = MinerRow { + brand: "Antminer".into(), + firmware: "Stock".into(), + cpu: "XIL".into(), + board_code: "C49".into(), + ..Default::default() + }; + assert!(!is_unidentified_stock_antminer(&s17)); + // A non-Antminer is never flagged. + let wm = MinerRow { + brand: "WhatsMiner".into(), + firmware: "Stock".into(), + ..Default::default() + }; + assert!(!is_unidentified_stock_antminer(&wm)); + } + #[test] fn a_stock_a113d_bhb42xxx_is_an_install_target_despite_unknown_brand() { // Exactly as the live scan reports the bench A113D at 10.255.1.18: diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index c4e06f5e..a46e0981 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -533,8 +533,18 @@ pub fn start_scan(lines: Vec, timeout_secs: u64) -> ScanHandle { } // asic-rs does not recognise a board running Alkane // OS (no cgminer socket or vendor web UI exposed); - // the toolkit's own probe finds it. - None => (ip, crate::alkane_detect::detect(ip).await), + // the toolkit's own probe finds it. Failing that, + // a stock Antminer whose miner API is down is still + // found by its :80 vendor web UI. + None => { + let row = match crate::alkane_detect::detect(ip).await { + Some(r) => Some(r), + None => { + crate::alkane_detect::detect_stock_antminer(ip).await + } + }; + (ip, row) + } } } }) diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index 72ef4fa4..57cb243e 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -221,8 +221,10 @@ pub fn start_install( } AfwSource::Release { name, url } => { let _ = tx.send(StockMsg::Progress("acquiring .afw...".into())); + // Token attaches only for the trusted gitea host (see + // for_asset_url); never sent to a GitHub/other fork host. match fetch::fetch_afw_url( - &ReleaseSource::alkane_os(), + &ReleaseSource::for_asset_url(&url), &name, &url, &download_dir(), diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 5de2209f..ff386df9 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -120,6 +120,9 @@ const ID_MEDIA_KIND_CHOICE: i32 = 1017; const ID_MEDIA_DEVICE_CHOICE: i32 = 1019; const ID_MEDIA_BROWSE: i32 = 1020; const ID_MEDIA_RELOAD_DEVS: i32 = 1022; +// Install dialog control-board selector (lets the operator pick/override the +// control board, needed when the scan could not determine it). +const ID_INSTALL_BOARD_CHOICE: i32 = 1023; const ID_INSTALL_OK: i32 = 1006; const ID_INSTALL_CANCEL: i32 = 1007; const ID_INSTALL_RELEASE_CHOICE: i32 = 1008; @@ -1011,6 +1014,7 @@ pub struct App { stock_op: Option, install_dialog: Widget, install_release_choice: Widget, + install_board_choice: Widget, install_unsigned_check: Widget, install_releases: Vec, install_ips: Vec, @@ -1461,6 +1465,7 @@ pub fn build(frame: Widget) -> App { stock_op: None, install_dialog: frame, install_release_choice: frame, + install_board_choice: frame, install_unsigned_check: frame, install_releases: Vec::new(), install_ips: Vec::new(), @@ -2084,7 +2089,13 @@ impl App { // - Uninstall: a board running Alkane OS (restored to stock). // A mixed stock/Alkane selection gets neither Install nor Update. The // engine still gates on compatibility. - let supported = selected.iter().all(|r| alkane_detect::install_supported(r)); + // Offer install when every selected board is either a known supported + // control board, or a stock Antminer whose control board is unknown + // (found by its :80 web UI) -- the latter installs with a manually + // chosen control board in the dialog. + let supported = selected.iter().all(|r| { + alkane_detect::install_supported(r) || alkane_detect::is_unidentified_stock_antminer(r) + }); let all_alkane = selected.iter().all(|r| alkane_detect::is_alkane(r)); let none_alkane = selected.iter().all(|r| !alkane_detect::is_alkane(r)); let install = supported && none_alkane; @@ -2839,27 +2850,25 @@ impl App { /// that carry an .afw compatible with the target board (newest first). Called /// when the dialog opens and from the Reload button. Requires /// `install_release_choice` to already exist. - fn populate_install_releases(&mut self, owner: &str, repo: &str) { + fn populate_install_releases(&mut self, src: &ReleaseSource) { let board = self.install_board.clone(); - wx_rs::set_status_text(&format!("scanning {owner}/{repo} releases...")); - let releases: Vec = - match fetch::list_releases(&ReleaseSource::for_repo(owner, repo)) { - Ok(list) => list - .into_iter() - .filter(|r| !r.draft && r.is_compatible_with(&board)) - .collect(), - Err(e) => { - wx_rs::set_status_text(&format!("could not list {owner}/{repo} releases: {e}")); - Vec::new() - } - }; + let label = format!("{}/{}", src.owner, src.repo); + wx_rs::set_status_text(&format!("scanning {label} releases...")); + let releases: Vec = match fetch::list_releases(src) { + Ok(list) => list + .into_iter() + .filter(|r| !r.draft && r.is_compatible_with(&board)) + .collect(), + Err(e) => { + wx_rs::set_status_text(&format!("could not list {label} releases: {e}")); + Vec::new() + } + }; self.install_releases = releases; let choice = self.install_release_choice; choice.choice_clear(); if self.install_releases.is_empty() { - choice.choice_append(&format!( - "(no release with an .afw for {board} in {owner}/{repo})" - )); + choice.choice_append(&format!("(no release with an .afw for {board} in {label})")); } else { for (i, r) in self.install_releases.iter().enumerate() { let tag = if r.tag.is_empty() { @@ -2875,24 +2884,18 @@ impl App { choice.choice_set_selection(0); } wx_rs::set_status_text(&format!( - "{} release(s) for {board} in {owner}/{repo}", + "{} release(s) for {board} in {label}", self.install_releases.len() )); } - /// Reload the install picker from the owner/repo currently typed in the - /// dialog's repo field (default blueflare/alkane-os if blank/malformed). + /// Reload the install picker from the repo URL currently typed in the + /// dialog's repo field. Accepts a full Gitea or GitHub repo URL (or a bare + /// `owner/repo` on the default Gitea); falls back to blueflare/alkane-os. fn reload_install_repo(&mut self) { let raw = self.install_repo_input.get_value(); - let raw = raw.trim(); - let (owner, repo) = raw.split_once('/').unwrap_or(("blueflare", "alkane-os")); - let owner = owner.trim(); - let repo = repo.trim(); - if owner.is_empty() || repo.is_empty() { - self.populate_install_releases("blueflare", "alkane-os"); - } else { - self.populate_install_releases(owner, repo); - } + let src = ReleaseSource::from_url(raw.trim()).unwrap_or_else(ReleaseSource::alkane_os); + self.populate_install_releases(&src); self.install_dialog.layout(); } @@ -2953,12 +2956,35 @@ impl App { sf::BORDER_ALL, 12, ); + // Control-board selector: defaults to the detected board, but the + // operator can override it -- required when the scan could not determine + // the control board (a stock Antminer found only by its :80 web UI). root.add( - Widget::static_text(dlg, &format!("Target board: {board}")), + Widget::static_text(dlg, "Control board:"), 0, - sf::BORDER_LEFT | sf::BORDER_RIGHT, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); + let board_choice = Widget::choice(dlg, ID_INSTALL_BOARD_CHOICE); + let mut board_sel = 0; + for (i, (id, desc)) in stock_ops::SUPPORTED_BOARDS.iter().enumerate() { + board_choice.choice_append(&format!("{id} -- {desc}")); + if *id == board { + board_sel = i as i32; + } + } + board_choice.choice_set_selection(board_sel); + root.add( + board_choice, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + self.install_board_choice = board_choice; + // Keep install_board consistent with the selector's initial choice. + if let Some((id, _)) = stock_ops::SUPPORTED_BOARDS.get(board_sel as usize) { + self.install_board = id.to_string(); + } root.add( Widget::static_text( dlg, @@ -2985,14 +3011,14 @@ impl App { // format; defaults to blueflare/alkane-os. Reload re-scans it and keeps // only the releases compatible with this board. root.add( - Widget::static_text(dlg, "Release repo (owner/repo), then Reload:"), + Widget::static_text(dlg, "Release repo URL (Gitea or GitHub), then Reload:"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); let repo_row = Widget::box_sizer(false); let repo_input = Widget::text_ctrl(dlg, false); - repo_input.set_value("blueflare/alkane-os"); + repo_input.set_value("https://gitea.bluefla.re/blueflare/alkane-os"); repo_row.add( repo_input, 1, @@ -3008,7 +3034,7 @@ impl App { 12, ); // Initial population from the default repo. - self.populate_install_releases("blueflare", "alkane-os"); + self.populate_install_releases(&ReleaseSource::alkane_os()); // Or install from a local .afw the operator picks (the CLI's local-file // install, now in the GUI). When a file is chosen it takes precedence @@ -3298,7 +3324,13 @@ impl App { self.install_dialog.close(0); return; } - let board = self.install_board.clone(); + // Take the control board from the selector (the operator may have picked + // or overridden it, e.g. for a stock Antminer the scan could not identify). + let board = stock_ops::SUPPORTED_BOARDS + .get(self.install_board_choice.choice_get_selection().max(0) as usize) + .map(|(id, _)| id.to_string()) + .unwrap_or_else(|| self.install_board.clone()); + self.install_board = board.clone(); // Source: a local .afw the operator picked takes precedence; otherwise // the selected Gitea release's asset for this board. let (source, source_name) = if let Some(path) = self.install_local_path.clone() { @@ -6470,6 +6502,14 @@ impl App { self.filter_pending_op = Some(sel); wx_rs::call_after(DEFER_FILTER); } + ID_INSTALL_BOARD_CHOICE => { + // The operator changed the target control board: re-filter the + // release picker for the new board. + if let Some((board, _)) = stock_ops::SUPPORTED_BOARDS.get(sel.max(0) as usize) { + self.install_board = board.to_string(); + self.reload_install_repo(); + } + } _ => {} } }