diff --git a/ci/make-afw.sh b/ci/make-afw.sh new file mode 100644 index 0000000..7ccf830 --- /dev/null +++ b/ci/make-afw.sh @@ -0,0 +1,68 @@ +#!/bin/sh +# Build an .afw firmware package for one control board and architecture. +# +# Modelled on the Warden `.wfw` bundle (scada/flare-edge/docs/firmware-format.md): +# one file, a strict POSIX ustar tar, a JSON manifest first, then the payload, +# with the payload's size and sha256 in the manifest so the device can verify +# before it touches flash. +# +# Differences from .wfw, both deliberate: +# +# * the payload is COMPRESSED (`payload.tar.gz`) because these images ship to +# boards over metered links, and a firmware bundle is mostly redundant; +# * the manifest carries `board` and `arch`, and both go in the file name, so a +# bundle can never be mistaken for another board family. Flashing the wrong +# family is how boards are lost. +# +# Signature: `.wfw` carries an Ed25519 detached signature. We have no release +# key yet, so `.afw` currently ships `members=2` and says so in the manifest +# (`signature: "unsigned"`). Do not claim integrity beyond the sha256 until a +# key exists. +# +# usage: make-afw.sh BOARD ARCH VERSION INPUT_DIR [OUTPUT_DIR] +# e.g. make-afw.sh am335x-bb armv7 0.1.0 /tmp/release +set -eu + +BOARD=${1:?board family, e.g. am335x-bb} +ARCH=${2:?architecture, e.g. armv7 or aarch64} +VERSION=${3:?version, e.g. 0.1.0} +INPUT=${4:?directory holding the release files} +OUTPUT=${5:-dist} + +mkdir -p "$OUTPUT" +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +# The payload is a tar of the release tree, gzipped at maximum. +tar --format=ustar --owner=0 --group=0 --numeric-owner \ + --create --file "$WORK/payload.tar" -C "$INPUT" . +gzip -9 -n -c "$WORK/payload.tar" > "$WORK/payload.tar.gz" + +PAYLOAD_SIZE=$(wc -c < "$WORK/payload.tar.gz") +PAYLOAD_SHA=$(sha256sum "$WORK/payload.tar.gz" | cut -d' ' -f1) +BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ") + +cat > "$WORK/manifest.json" < CapSet { + CapSet::new(["hashboard", "psu", "fan-map", "cgminer-api"]) +} + +/// The dashboard: an effective schema plus the stored rows. +pub struct Dashboard { + effective: Result, + rows: Rows, + path: PathBuf, +} + +impl Dashboard { + /// Load the schema and the stored settings, defaulting absent rows to the + /// schema's own defaults. + pub fn load(path: impl AsRef) -> Dashboard { + let path = path.as_ref().to_path_buf(); + let effective = Document::from_json(SCHEMA) + .map_err(|error| error.to_string()) + .and_then(|doc| { + effective::merge(&doc, &[]).map_err(|errors| { + errors + .iter() + .map(|error| error.msg.clone()) + .collect::>() + .join("; ") + }) + }); + let mut rows = Rows::new(); + if let Ok(text) = fs::read_to_string(&path) { + if let Ok(Value::Object(map)) = serde_json::from_str::(&text) { + for (key, value) in map { + rows.insert(key, value); + } + } + } + Dashboard { + effective, + rows, + path, + } + } + + pub fn schema(&self) -> Result<&Effective, String> { + self.effective.as_ref().map_err(|error| error.clone()) + } + + pub fn rows(&self) -> &Rows { + &self.rows + } + + /// The visible navigation for this board and viewer. + pub fn nav(&self) -> Result { + let effective = self.effective.as_ref().map_err(|error| error.clone())?; + let caps = board_caps(); + let apps = AppSet::default(); + let routes = Routes::console(); + let ctx = NavContext { + surface: Surface::Web, + principal: &AllowAll, + caps: &caps, + apps: &apps, + routes: &routes, + }; + Ok(nav::visible(&effective.doc.menus, &ctx)) + } + + /// Stylesheets the shell needs, served from the crate's embedded assets. + pub fn assets() -> PageAssets { + PageAssets { + styles: vec![ + "/assets/tokens.css".to_string(), + "/assets/components.css".to_string(), + "/assets/theme.css".to_string(), + ], + scripts: Vec::new(), + streams: Vec::new(), + } + } + + /// The three stylesheets, for the host to serve. + pub fn stylesheets() -> [(&'static str, &'static str); 3] { + [ + ("tokens.css", tokens::TOKENS_CSS), + ("components.css", tokens::COMPONENTS_CSS), + ("theme.css", tokens::THEME_CSS), + ] + } + + /// Render one page: the shell around the settings card of the tab. + /// + /// `section` is the navigation section (`settings`), `tab` the tab slug + /// (`tuning`), and the settings card shows the group named by the tab. + /// + /// `errors` carries per-path messages from a rejected submission, so the + /// same render can show what went wrong. + pub fn page(&self, section: &str, tab: &str, errors: &BTreeMap) -> Markup { + let effective = match self.effective.as_ref() { + Ok(effective) => effective, + Err(error) => { + return maud::html! { + main class="bf-main" { + p class="bf-field-error bf-text-body" role="alert" { "Schema did not load: " (error) } + } + } + } + }; + let nav = self.nav().unwrap_or_default(); + let view = View { + eff: effective, + rows: &self.rows, + errors, + surface: Surface::Web, + can_write: true, + }; + let title = effective + .doc + .menus + .iter() + .find(|menu| menu.slug == tab && menu.id.starts_with(&format!("{section}/"))) + .map(|menu| menu.title.clone()) + .unwrap_or_else(|| section.to_string()); + let card = render::card(&title, tab, &view); + let body = maud::html! { + section class="bf-card" { + h1 class="bf-text-title" { (title) } + (card) + } + }; + shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body) + } + + /// Apply a submitted form body (`application/x-www-form-urlencoded`). + /// + /// Returns the per-path failures when the schema rejects the batch, and + /// persists nothing in that case. Unknown keys are ignored: they are not in + /// the schema, so they cannot be written. + pub fn submit(&mut self, body: &str) -> Result<(), BTreeMap> { + let effective = match self.effective.as_ref() { + Ok(effective) => effective, + Err(error) => { + let mut failures = BTreeMap::new(); + failures.insert(String::new(), error.clone()); + return Err(failures); + } + }; + let ops = self.parse_ops(effective, body); + let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None); + if !failures.is_empty() { + return Err(failures); + } + for op in &ops { + if let Op::Set { path, value } = op { + self.rows.insert(path.clone(), value.clone()); + } + } + let map: Map = self + .rows + .iter() + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into()); + if let Some(parent) = self.path.parent() { + let _ = fs::create_dir_all(parent); + } + // Persist only after validation passed; a failed write leaves the rows + // changed in memory but never on disk, which the API reports. + let _ = fs::write(&self.path, text); + Ok(()) + } + + /// Turn a form body into schema ops, coercing each value to its declared kind. + fn parse_ops(&self, effective: &Effective, body: &str) -> Vec { + let mut ops = Vec::new(); + for pair in body.split('&') { + if pair.is_empty() { + continue; + } + let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, "")); + let key = percent_decode(raw_key); + let raw = percent_decode(raw_value); + let setting = match effective.setting(&key) { + Some(setting) => setting, + None => continue, + }; + let value = coerce(setting.kind.token(), &raw); + ops.push(Op::Set { + path: setting.path.clone(), + value, + }); + } + ops + } +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'+' => { + out.push(b' '); + index += 1; + } + b'%' if index + 2 < bytes.len() => { + let high = (bytes[index + 1] as char).to_digit(16); + let low = (bytes[index + 2] as char).to_digit(16); + match (high, low) { + (Some(high), Some(low)) => { + out.push((high * 16 + low) as u8); + index += 3; + } + _ => { + out.push(bytes[index]); + index += 1; + } + } + } + byte => { + out.push(byte); + index += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +fn coerce(kind: &str, raw: &str) -> Value { + match kind { + "int" | "int_set" => raw + .trim() + .parse::() + .map(Value::from) + .unwrap_or_else(|_| Value::String(raw.to_string())), + "bool" => Value::Bool(matches!(raw, "true" | "on" | "1")), + _ => Value::String(raw.to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_path(name: &str) -> PathBuf { + let mut path = std::env::temp_dir(); + path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id())); + let _ = fs::remove_file(&path); + path + } + + #[test] + fn the_schema_loads_and_yields_the_three_sections() { + let dash = Dashboard::load(temp_path("load")); + let effective = dash.schema().expect("schema loads"); + assert_eq!(effective.doc.menus.len(), 17); + let nav = dash.nav().expect("nav builds"); + assert_eq!(nav.sections.len(), 3); + assert_eq!(nav.sections[1].slug, "mining"); + assert_eq!(nav.sections[1].tabs.len(), 4); + } + + #[test] + fn every_scaffolded_setting_is_in_the_schema() { + let dash = Dashboard::load(temp_path("settings")); + let effective = dash.schema().expect("schema loads"); + for path in [ + "tuning.mode", + "tuning.power_w", + "tuning.ceiling_mc", + "tuning.pid.kp_milli", + "tuning.pid.deadband_milli", + "fans.zone_count", + "fans.pwm_min", + "detect.chain_ports", + "detect.probe_budget", + "profiles.db", + "system.name", + ] { + assert!(effective.setting(path).is_some(), "{path} is missing from the schema"); + } + assert_eq!(effective.doc.settings.len(), 20); + } + + #[test] + fn a_page_renders_its_settings_with_inputs() { + let dash = Dashboard::load(temp_path("page")); + let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string(); + assert!(html.contains("bf-sidebar"), "the unified sidebar is missing"); + assert!(html.contains("bf-tabs"), "the tab strip is missing"); + assert!(html.contains("Tuning target"), "a settings label is missing"); + assert!(html.contains("tuning.power_w"), "the field path is missing"); + assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing"); + } + + #[test] + fn a_valid_submission_is_persisted_and_reloaded() { + let path = temp_path("submit"); + let mut dash = Dashboard::load(&path); + dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form"); + assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500))); + let stored = fs::read_to_string(&path).expect("settings file written"); + assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}"); + let reloaded = Dashboard::load(&path); + assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro"))); + let _ = fs::remove_file(&path); + } + + #[test] + fn an_out_of_range_value_is_rejected_and_nothing_is_written() { + let path = temp_path("reject"); + let mut dash = Dashboard::load(&path); + let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected"); + assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}"); + assert!(!path.exists(), "a rejected submission must not be persisted"); + assert_eq!(dash.rows().get("tuning.power_w"), None); + } + + #[test] + fn unknown_form_keys_are_ignored() { + let path = temp_path("unknown"); + let mut dash = Dashboard::load(&path); + dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies"); + assert_eq!(dash.rows().get("not.a.setting"), None); + assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650))); + let _ = fs::remove_file(&path); + } + + #[test] + fn form_values_are_percent_decoded() { + assert_eq!(percent_decode("a+b%2Fc"), "a b/c"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 7888392..73791bf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod bm1366; pub mod bm1370; pub mod bm13xx; pub mod detect; +pub mod dashboard; pub mod difficulty; pub mod fanmap; pub mod fanmap_store; diff --git a/src/web.rs b/src/web.rs index c473ccc..eaf9f53 100644 --- a/src/web.rs +++ b/src/web.rs @@ -163,6 +163,9 @@ pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> { } fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io::Result<()> { + if dashboard_route(stream, request)? { + return Ok(()); + } match (request.method.as_str(), request.path.as_str()) { ("GET", "/") => html(stream, "Dashboard", &ui::dashboard_page("dashboard", true)), ("GET", "/mining") => html( @@ -355,6 +358,72 @@ fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io } } + +/// Where the dashboard keeps operator settings. +fn settings_path() -> std::path::PathBuf { + let etc = std::path::Path::new("/etc/alkane/settings.json"); + if etc.exists() || std::path::Path::new("/etc/alkane").is_dir() { + return etc.to_path_buf(); + } + // A read-only root or a test run: keep the file beside the binary. + std::env::temp_dir().join("alkane-settings.json") +} + +/// Serve the schema-driven UI: assets, pages and the settings form. +/// +/// Returns `None` when the path is not a dashboard path, so the hand-written +/// API routes below keep working unchanged. +fn dashboard_route(stream: &mut TcpStream, request: &Request) -> io::Result { + let path = request.path.clone(); + if let Some(name) = path.strip_prefix("/assets/") { + for (file, css) in crate::dashboard::Dashboard::stylesheets() { + if name == file { + return respond(stream, 200, "text/css; charset=utf-8", css.as_bytes()).map(|_| true); + } + } + return Ok(false); + } + if request.method == "POST" && path == "/settings" { + let mut dash = crate::dashboard::Dashboard::load(settings_path()); + return match dash.submit(&request.body) { + Ok(()) => respond(stream, 303, "text/plain", b"see /").map(|_| true), + Err(failures) => { + let mut text = String::new(); + for (key, why) in failures { + text.push_str(&format!("{key}: {why}\n")); + } + respond(stream, 422, "text/plain; charset=utf-8", text.as_bytes()).map(|_| true) + } + }; + } + if request.method != "GET" { + return Ok(false); + } + let mut parts = path.trim_start_matches('/').split('/'); + let section = match parts.next() { + Some(section) if !section.is_empty() => section, + _ => return Ok(false), + }; + let dash = crate::dashboard::Dashboard::load(settings_path()); + let nav = match dash.nav() { + Ok(nav) => nav, + Err(_) => return Ok(false), + }; + let known = nav.sections.iter().find(|s| s.slug == section); + let known = match known { + Some(section) => section, + None => return Ok(false), + }; + let tab = parts.next().unwrap_or_else(|| { + known.tabs.first().map(|tab| tab.slug.as_str()).unwrap_or("") + }); + if !known.tabs.iter().any(|t| t.slug == tab) { + return Ok(false); + } + let html = dash.page(section, tab, &std::collections::BTreeMap::new()).into_string(); + respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()).map(|_| true) +} + fn html(stream: &mut TcpStream, title: &str, body: &str) -> io::Result<()> { let page = ui::page(path_for(title), title, body); respond(stream, 200, "text/html; charset=utf-8", page.as_bytes())