diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs b/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs index 858eb610e7..0d9b551942 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs @@ -21,9 +21,11 @@ pub fn identity(app: &AppHandle) -> Result { fn identity_at(resources: &Path) -> Result { let path = resources.join("runtime/identity.json"); - let value: Value = - serde_json::from_slice(&fs::read(path).map_err(|_| "runtime_bundle_missing")?) - .map_err(|_| "runtime_bundle_invalid")?; + parse_identity(&fs::read(path).map_err(|_| "runtime_bundle_missing")?) +} + +pub(crate) fn parse_identity(bytes: &[u8]) -> Result { + let value: Value = serde_json::from_slice(bytes).map_err(|_| "runtime_bundle_invalid")?; if value["schema_version"] != "desktop_runtime_bundle_v1" || !value["source_revision"] .as_str() diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs index 4a876cbb2b..16c07501b0 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs @@ -3,13 +3,57 @@ //! the existing updater. This is only its macOS filesystem effect adapter. use std::{ fs, - io::{self, Cursor}, + io::{self, Cursor, Read}, path::{Component, Path}, }; use flate2::read::GzDecoder; +use serde_json::Value; use tauri_plugin_updater::Update; +const PUBLIC_DEFAULT_CONTRACT: &str = + include_str!("../../../../../loopx/cli_commands/public_default_contract.json"); + +/// Read the publisher's observed contract inside the signature-verified bytes +/// before an update can be cached, close the workspace, or replace its App. +pub(crate) fn qualify_candidate( + channel: &str, + version: &str, + verified_bytes: &[u8], +) -> Result<(), String> { + // Historical stable bundles predate the attestation and remain usable. + // A preview stays subject to the check even if cache metadata changes channel. + if channel != "main" + && !semver::Version::parse(version) + .is_ok_and(|value| value.pre.as_str().starts_with("main.")) + { + return Ok(()); + } + let invalid = "runtime_bundle_invalid"; + let unavailable = "update_platform_unavailable"; + let supported: Value = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).map_err(|_| invalid)?; + let identity_path = Path::new("LoopX.app/Contents/Resources/runtime/identity.json"); + let mut archive = tar::Archive::new(GzDecoder::new(Cursor::new(verified_bytes))); + let mut qualified = false; + for entry in archive.entries().map_err(|_| invalid)? { + let mut entry = entry.map_err(|_| invalid)?; + if entry.path().map_err(|_| invalid)? != identity_path { + continue; + } + if qualified || !entry.header().entry_type().is_file() || entry.size() > 16 * 1024 { + return Err(invalid.into()); + } + let mut raw = Vec::new(); + entry.read_to_end(&mut raw).map_err(|_| invalid)?; + let identity = crate::bundled_runtime::parse_identity(&raw)?; + if identity["default_contract"] != supported { + return Err(unavailable.into()); + } + qualified = true; + } + qualified.then_some(()).ok_or_else(|| unavailable.into()) +} + // Provider-local errors, never a new persisted or caller-facing vocabulary. #[derive(Debug, PartialEq)] enum InstallError { @@ -132,6 +176,55 @@ mod tests { builder.into_inner().unwrap().finish().unwrap() } + #[test] + fn only_qualified_preview_can_replace_the_prepared_candidate() { + let root = tempfile::tempdir().unwrap(); + let candidate = root.path().join("candidate"); + let resources = candidate.join("Contents/Resources/runtime"); + fs::create_dir_all(&resources).unwrap(); + let cache = root.path().join("prepared"); + let version = "0.0.0-main.2.1"; + let identity_path = resources.join("identity.json"); + let mut identity = serde_json::json!({ + "schema_version": "desktop_runtime_bundle_v1", + "source_revision": "1111111111111111111111111111111111111111" + }); + let rejected = [ + None, + Some(serde_json::json!({"surface": "unknown"})), + Some(serde_json::json!({ + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0" + })), + ]; + for contract in rejected { + if let Some(contract) = contract { + identity["default_contract"] = contract; + } + fs::write(&identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + assert_eq!( + crate::prepared_update::save(&cache, "main", version, "unused", &bytes), + Err("update_platform_unavailable".into()) + ); + assert!(!cache.exists()); + assert_eq!( + qualify_candidate("stable", version, &bytes), + Err("update_platform_unavailable".into()) + ); + assert!(qualify_candidate("stable", "2.3.0", &bytes).is_ok()); + } + + identity["default_contract"] = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).unwrap(); + fs::write(identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + crate::prepared_update::save(&cache, "main", version, "unused", &bytes).unwrap(); + let pointer = fs::read(cache.join("prepared.json")).unwrap(); + assert!(crate::prepared_update::save(&cache, "main", version, "unused", b"bad").is_err()); + assert_eq!(fs::read(cache.join("prepared.json")).unwrap(), pointer); + } + #[test] fn verified_candidate_replaces_app_and_retains_intact_previous_bundle() { let root = tempfile::tempdir().unwrap(); diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs index 09b438f266..e94f056365 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs @@ -896,14 +896,27 @@ async fn perform( let bytes = if let Some(cached) = cached { cached.bytes } else { - download_update(&update, |chunk, total| { + let bytes = download_update(&update, |chunk, total| { received += chunk as u64; state.publish( "downloading", json!({"received":received,"total":total,"version":update.version}), ); }) - .await? + .await?; + #[cfg(target_os = "macos")] + { + let version = update.version.clone(); + let channel = channel.to_owned(); + tauri::async_runtime::spawn_blocking(move || { + crate::macos_update::qualify_candidate(&channel, &version, &bytes)?; + Ok::<_, String>(bytes) + }) + .await + .map_err(|_| "runtime_bundle_invalid".to_string())?? + } + #[cfg(not(target_os = "macos"))] + bytes }; let target = update.version.clone(); install_verified_app(app, target, move || { diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs index 2085a3ba7a..07e596e2a1 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs @@ -75,6 +75,8 @@ pub(crate) fn save( if !matches!(channel, "main" | "stable") || semver::Version::parse(version).is_err() { return Err(INVALID.into()); } + #[cfg(target_os = "macos")] + crate::macos_update::qualify_candidate(channel, version, bytes)?; fs::create_dir_all(root).map_err(|_| INVALID)?; let old = metadata(root).ok().flatten(); let value = json!({"schema_version":"desktop_prepared_update_v1", "channel":channel, @@ -156,6 +158,8 @@ fn read( let signature = Signature::decode(std::str::from_utf8(&signature).map_err(|_| INVALID)?) .map_err(|_| INVALID)?; key.verify(&bytes, &signature, true).map_err(|_| INVALID)?; + #[cfg(target_os = "macos")] + crate::macos_update::qualify_candidate(channel, version, &bytes)?; Ok(Some(PreparedUpdate { version: version.into(), signature: value["signature"].as_str().ok_or(INVALID)?.into(), diff --git a/loopx/cli_commands/public_default_contract.json b/loopx/cli_commands/public_default_contract.json new file mode 100644 index 0000000000..e62060503f --- /dev/null +++ b/loopx/cli_commands/public_default_contract.json @@ -0,0 +1,5 @@ +{ + "surface": "quota_packet", + "schema_version": null, + "interaction_schema_version": "loopx_interaction_contract_v0" +} diff --git a/loopx/cli_commands/update_artifact.py b/loopx/cli_commands/update_artifact.py index d4546b50f9..afc6555e61 100644 --- a/loopx/cli_commands/update_artifact.py +++ b/loopx/cli_commands/update_artifact.py @@ -31,8 +31,9 @@ from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN RUNTIME_ARTIFACT_SCHEMA_VERSION = "loopx_runtime_artifact_v1" -PUBLIC_DEFAULT_CONTRACT = {"surface": "quota_packet", "schema_version": None, - "interaction_schema_version": "loopx_interaction_contract_v0"} +PUBLIC_DEFAULT_CONTRACT = json.loads( + Path(__file__).with_name("public_default_contract.json").read_text(encoding="utf-8") +) SHA = re.compile(r"[0-9a-f]{40}") MAX_MANIFEST = 256 * 1024 MAX_ARCHIVE = 256 * 1024 * 1024 @@ -61,7 +62,15 @@ def standalone_source() -> str: if source.count(old) != 1: raise ValueError("Bootstrap grammar binding no longer matches its source import") source = source.replace(old, "\n" + binding + "\n", 1) - return source + # The public installer is one file, so embed the policy that the Python + # publishers and the native updater read from the distribution contract. + binding_start = source.index("\nPUBLIC_DEFAULT_CONTRACT = ") + binding_end = source.index("\nSHA = ", binding_start) + return ( + source[:binding_start] + + f"\nPUBLIC_DEFAULT_CONTRACT = {PUBLIC_DEFAULT_CONTRACT!r}" + + source[binding_end:] + ) def safe_url(url: str) -> str: diff --git a/pyproject.toml b/pyproject.toml index 623d084858..e0f4a62e08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -81,6 +81,7 @@ include = ["loopx*"] [tool.setuptools.package-data] "loopx" = ["web/chat/*.html", "web/chat/*.json", "web/chat/assets/*", "web/chat/manifest.webmanifest", "web/chat/pwa/*"] +"loopx.cli_commands" = ["public_default_contract.json"] "loopx.control_plane" = ["*.json", "*.ts", "presentation/*.ts"] "loopx.semantics" = ["*.json"] "loopx.control_plane.agents" = ["*.ts"]