diff --git a/Cargo.lock b/Cargo.lock index 308e77b..aaf2be6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -654,7 +654,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jaynshare" -version = "2.3.1" +version = "2.3.2" dependencies = [ "base64", "bytes", diff --git a/Cargo.toml b/Cargo.toml index ee9ea1f..7cf87cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "jaynshare" -version = "2.3.1" +version = "2.3.2" edition = "2024" rust-version = "1.95" publish = false diff --git a/README.md b/README.md index 7cbbf76..062ad8e 100644 --- a/README.md +++ b/README.md @@ -179,10 +179,12 @@ own `codex login`; the pool replaces it on every request. ### Claude Desktop Chat on macOS On an enrolled Mac, install Claude Desktop in `/Applications` or -`~/Applications` and quit the app fully. Run `jaynshare trust-ca add` to trust -the pool's current interception CA in macOS, then start the connection from a -terminal. If a CA rotation is staged, also import and trust that next root from -the enrollment's `ca.pem`; Desktop checks both roots before setup. +`~/Applications` and quit the app fully, then start the connection from a +terminal. When the pool's CA is missing from macOS trust, the command shows its +fingerprint and asks `Install CA globally (needed for Claude Desktop) [y/N]`. +Answer `y` to install it in your login keychain and continue; Enter or `n` +cancels the launch. A staged replacement CA gets the same confirmation if it +is not already trusted. Desktop checks both roots before setup. ```sh jaynshare desktop # Anthropic account picker @@ -207,12 +209,20 @@ Changing accounts never requires quitting Desktop. With `--auto`, existing sessions keep their server-side account binding; an exhausted account returns an error instead of switching accounts by itself. -The integration checks Desktop **2.26454.0 with Claude Code 2.1.289**, and -**2.26454.2 or 2.31226.0 with Claude Code 2.1.293**. The 2.31226.0 profile and -startup/title contracts were verified from its installed bundle with mocked -transport; a live Chat test completed on 2.31226.0 before the egress changes. -Other versions, ambiguous managed runtimes, untrusted pool CAs and managed -device policies produce a clear error before profile setup. +Desktop versions are checked automatically. Jaynshare reads the managed runtime +version and bundle checksum from Desktop's installed bundle, checks the matching +verified runtime and runs a synthetic streaming exchange against a temporary +local gateway. This check uses no pooled account, sends no user prompt and runs +once per adapter launch. On first startup it runs after runtime provisioning, +before engine inference is forwarded. Invalid bundle metadata, mismatched runtime +verification, failed checks, untrusted pool CAs and managed device policies +produce a clear error. Existing runtimes are checked before profile setup. +This verifies the engine's protocol, not every Desktop UI feature. Desktop's +private profile format and startup/title contracts can still change and require +a Jaynshare update. The native app blocks ordinary remote debugging and custom +test profiles, so this check does not drive the GUI. The 2.31226.0 profile and +startup/title contracts were inspected from its installed bundle, and its genuine +Claude Code 2.1.293 runtime passed the local streaming check. An app or verified runtime replacement stops the adapter; quit Desktop fully and relaunch the command to check compatibility again. @@ -222,8 +232,9 @@ uses your enrollment and server identity pin internally. Its native `egressProxyUrl` points at the same loopback listener; the relay adds the proxy credential only on its connection to the server. Desktop requires macOS CA trust and receives `NODE_EXTRA_CA_CERTS` for its child engine. Setup leaves the -system proxy and trust store untouched. Only **Chat** is in scope. Desktop lists the models the pool's -accounts offer through `/v1/models`, and the upstream refuses those an account +system proxy untouched and installs missing CAs only after confirmation. Only +**Chat** is in scope. Desktop lists the models the pool's accounts offer through +`/v1/models`, and the upstream refuses those an account cannot use; live Chat was checked with Sonnet 4.6. Text and explicitly permitted local-file access were exercised in the compatibility experiment; uploaded images, PDFs and text attachments, Cowork, Code, Chrome, connectors, @@ -246,7 +257,8 @@ credential; other page requests use opaque tunnels. The relay has no direct fallback when the VPS is unavailable. Native app and engine routing, first-run downloads and IPv4/IPv6 failure behavior still need a traffic audit; a strict guarantee covering every process requires an OS egress policy. The Jaynshare -profile disables Desktop auto-updates; install a checked newer version manually. +profile disables Desktop auto-updates; install a newer version manually, then +relaunch Jaynshare to run its compatibility checks. Upgrading an existing profile requires stopping the adapter and quitting Desktop fully before setup adds the proxy and update settings and enables model discovery. Repeat the trust check and fully relaunch after CA rotation. diff --git a/docs/security-and-privacy.md b/docs/security-and-privacy.md index 5aaa813..ebe8f32 100644 --- a/docs/security-and-privacy.md +++ b/docs/security-and-privacy.md @@ -170,11 +170,20 @@ or `jaynshare codex` launches, through `NODE_EXTRA_CA_CERTS` or `CODEX_CA_CERTIFICATE`. Outside Windows, a Codex launch also sets `CURL_CA_BUNDLE` to the system's roots plus the CA, so Codex's updater can fetch its installer; any `curl` run under that Codex trusts the CA too. It -enters the operating system's trust store only if the engineer runs -`jaynshare trust-ca add`, which always asks first. Desktop +enters the operating system's trust store only after confirmation through +`jaynshare trust-ca add` or Desktop's inline +`Install CA globally (needed for Claude Desktop) [y/N]` prompt. Desktop requires macOS trust for both current and staged roots before profile setup; +Enter or `n` cancels, and `--yes` does not bypass this confirmation. `trust-ca add` installs only the current root. Desktop's launch also supplies the CA bundle to its engine through `NODE_EXTRA_CA_CERTS`. +Desktop runtime compatibility uses the installed bundle's embedded version and +checksum, its matching `.verified` marker and a bounded synthetic streaming +exchange with a local mock gateway. The check has a fresh temporary profile, +no tools, no enrolled credential and no pooled-account usage. It does not certify +Desktop's private profile or GUI contracts; changed packaging or protocols can +require a Jaynshare update. Application and checked-runtime replacement still +stop the adapter. Desktop's egress relay refuses its local Gateway bearer in every Authorization value, including duplicate headers and alternate casing; destination credentials continue through the proxy. diff --git a/src/cli/help.rs b/src/cli/help.rs index f2670b1..8bef8ad 100644 --- a/src/cli/help.rs +++ b/src/cli/help.rs @@ -75,7 +75,7 @@ pub(super) static DOCS: &[VerbDoc] = &[ "desktop", Engineer, None, - "Open macOS Claude Desktop Chat through a foreground Gateway that monitors the pool's accounts; its arrow keys and Enter switch account, and closing this command stops the connection. Quit Desktop fully before initial setup", + "Open macOS Claude Desktop Chat through a foreground Gateway that monitors the pool's accounts; its arrow keys and Enter switch account, and closing this command stops the connection. Quit Desktop fully before initial setup; missing pool CAs are installed in macOS trust only after confirmation", [4, 5, 6, 7, 11, 15, 16], [ "jaynshare desktop", diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 47b789d..d74dd43 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -56,6 +56,7 @@ pub(crate) use control::{ }; use help::Role; pub(crate) use update::follow; +pub(crate) use verbs::confirm; use verbs::{ account_add, account_availability, account_list, account_login, account_remove, account_rename, account_replace, account_show, api, ca_export, ca_rotate, ca_show, client_list, client_rename, diff --git a/src/cli/verbs.rs b/src/cli/verbs.rs index b4d7af1..a604fb1 100644 --- a/src/cli/verbs.rs +++ b/src/cli/verbs.rs @@ -1590,7 +1590,7 @@ pub(super) fn typed_line(prompt: &str) -> Result { } /// A skippable confirmation on the controlling terminal. -pub(super) fn confirm(prompt: &str) -> Result { +pub(crate) fn confirm(prompt: &str) -> Result { if !std::io::stdin().is_terminal() { return Err(Failure::local( 21, diff --git a/src/desktop/app.rs b/src/desktop/app.rs index 00c1199..60c60fd 100644 --- a/src/desktop/app.rs +++ b/src/desktop/app.rs @@ -1,20 +1,20 @@ //! Compatibility checks against the installed app and its verified managed CLI. use std::path::{Path, PathBuf}; -use std::sync::OnceLock; use std::time::{Duration, SystemTime}; use tokio::process::Command; +use tokio::sync::OnceCell; -use super::config; +use super::{bundle, compatibility, config}; type Stamp = (u64, SystemTime); pub struct App { pub bundle: PathBuf, - runtime: OnceLock<(PathBuf, Vec<(PathBuf, Stamp)>)>, + runtime: OnceCell<(PathBuf, Vec<(PathBuf, Stamp)>)>, version: String, - runtime_version: &'static str, + expected_runtime: bundle::Runtime, stamps: Vec<(PathBuf, Stamp)>, } @@ -45,36 +45,38 @@ impl App { .arg(&plist), ) .await?; - // shortcut: this private profile format is checked only on these versions; recheck the native app before adding versions. - let runtime_version = match version.as_str() { - "2.26454.0" => "2.1.289", - "2.26454.2" | "2.31226.0" => "2.1.293", - _ => { - return Err(format!( - "Claude Desktop {version} has not been checked; supported versions: 2.26454.0, 2.26454.2 and 2.31226.0" - )); - } - }; - let stamps = [plist, bundle.join("Contents/Resources/app.asar")] + let archive = bundle.join("Contents/Resources/app.asar"); + let stamps = [plist, archive.clone()] .into_iter() .map(|path| stamp(&path).map(|stamp| (path, stamp))) .collect::>()?; + let expected_runtime = bundle::runtime(&archive)?; let app = Self { bundle, - runtime: OnceLock::new(), + runtime: OnceCell::new(), version, - runtime_version, + expected_runtime, stamps, }; - if runtime(runtime_version)?.is_some() { + app.unchanged()?; + if app.find_runtime()?.is_some() { app.runtime().await?; } Ok(app) } pub async fn runtime(&self) -> Result<&Path, String> { - if self.runtime.get().is_none() { - let runtime = runtime(self.runtime_version)?.ok_or("Desktop's managed runtime is still provisioning through the proxy; retry after its download finishes")?; + self.runtime.get_or_try_init(|| async { + let runtime = self.find_runtime()?.ok_or("Desktop's managed runtime is still provisioning through the proxy; retry after its download finishes")?; + let marker = runtime + .ancestors() + .nth(4) + .expect("managed bundle") + .join(".verified"); + let stamps: Vec<_> = [runtime.clone(), marker] + .into_iter() + .map(|path| stamp(&path).map(|stamp| (path, stamp))) + .collect::>()?; let actual = output( Command::new(&runtime) .arg("--version") @@ -83,23 +85,23 @@ impl App { .env("PATH", "/usr/bin:/bin"), ) .await?; - if actual.split_whitespace().next() != Some(self.runtime_version) { + if actual.split_whitespace().next() != Some(self.expected_runtime.version.as_str()) { return Err(format!( "the managed Claude Code runtime is incompatible; expected {}", - self.runtime_version + self.expected_runtime.version )); } - let marker = runtime - .ancestors() - .nth(4) - .expect("managed bundle") - .join(".verified"); - let stamps = [runtime.clone(), marker] - .into_iter() - .map(|path| stamp(&path).map(|stamp| (path, stamp))) - .collect::>()?; - let _ = self.runtime.set((runtime, stamps)); - } + compatibility::check(&runtime).await?; + if stamps + .iter() + .any(|(path, before)| stamp(path).as_ref() != Ok(before)) + { + return Err( + "Desktop's managed runtime changed during its compatibility check".into(), + ); + } + Ok::<_, String>((runtime, stamps)) + }).await?; self.unchanged()?; Ok(&self.runtime.get().expect("verified runtime").0) } @@ -113,7 +115,7 @@ impl App { stamps .iter() .any(|(file, before)| stamp(file).as_ref() != Ok(before)) - || runtime(self.runtime_version).as_ref() != Ok(&Some(path.clone())) + || self.find_runtime().as_ref() != Ok(&Some(path.clone())) }) { return Err(format!( @@ -124,6 +126,32 @@ impl App { Ok(()) } + fn find_runtime(&self) -> Result, String> { + let expected = &self.expected_runtime; + let directory = config::profile() + .join("claude-code") + .join(&expected.version); + let managed = directory.join(&expected.checksum[..12]); + let binary = managed.join("claude.app/Contents/MacOS/claude"); + let marker = managed.join(".verified"); + if !binary.is_file() || !marker.is_file() { + return Ok(None); + } + if std::fs::metadata(&marker).map_err(|e| e.to_string())?.len() > 128 { + return Err("Desktop's managed runtime verification marker is invalid".into()); + } + if std::fs::read_to_string(marker) + .map_err(|e| e.to_string())? + .trim() + != expected.checksum + { + return Err( + "Desktop's managed runtime verification does not match its bundled manifest".into(), + ); + } + Ok(Some(binary)) + } + pub async fn open(&self, ca: &Path) -> Result<(), String> { output( Command::new("open") @@ -136,27 +164,6 @@ impl App { } } -fn runtime(version: &str) -> Result, String> { - let directory = config::profile().join("claude-code").join(version); - let mut candidates = Vec::new(); - let entries = match std::fs::read_dir(&directory) { - Ok(entries) => entries, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(e) => return Err(format!("cannot read Desktop's managed runtime: {e}")), - }; - for entry in entries { - let path = entry.map_err(|e| e.to_string())?.path(); - let binary = path.join("claude.app/Contents/MacOS/claude"); - if path.join(".verified").is_file() && binary.is_file() { - candidates.push(binary); - } - } - if candidates.len() > 1 { - return Err("Desktop's active verified runtime is ambiguous".into()); - } - Ok(candidates.pop()) -} - fn stamp(path: &Path) -> Result { let metadata = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; Ok(( @@ -218,3 +225,19 @@ async fn output(command: &mut Command) -> Result { .map(|s| s.trim().to_string()) .map_err(|_| "invalid Desktop version output".into()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + #[ignore = "uses the installed macOS Desktop bundle and managed runtime"] + async fn installed_runtime_passes_local_streaming_check() { + let app = App::resolve() + .await + .expect("installed Desktop compatibility"); + app.runtime() + .await + .expect("managed runtime streaming check"); + } +} diff --git a/src/desktop/bundle.rs b/src/desktop/bundle.rs new file mode 100644 index 0000000..5694661 --- /dev/null +++ b/src/desktop/bundle.rs @@ -0,0 +1,215 @@ +//! Read Desktop's embedded runtime manifest without executing its JavaScript. + +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::Path; + +use serde_json::Value; + +#[derive(Debug)] +pub struct Runtime { + pub version: String, + pub checksum: String, +} + +pub fn runtime(path: &Path) -> Result { + read_runtime(path).map_err(|why| { + format!( + "cannot check Desktop's bundled runtime: {why}; update Jaynshare for this Desktop build" + ) + }) +} + +fn read_runtime(path: &Path) -> Result { + let mut archive = File::open(path).map_err(|e| e.to_string())?; + let length = archive.metadata().map_err(|e| e.to_string())?.len(); + let mut prefix = [0; 16]; + archive.read_exact(&mut prefix).map_err(|e| e.to_string())?; + let number = + |offset| u32::from_le_bytes(prefix[offset..offset + 4].try_into().expect("four bytes")); + let header_size = u64::from(number(4)); + let json_size = u64::from(number(12)); + let start = header_size + .checked_add(8) + .ok_or("archive header overflow")?; + if number(0) != 4 + || json_size > 8 * 1024 * 1024 + || json_size + 8 > header_size + || start > length + { + return Err("invalid app.asar header".into()); + } + let mut bytes = vec![0; json_size as usize]; + archive.read_exact(&mut bytes).map_err(|e| e.to_string())?; + let header: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + let files = header["files"][".vite"]["files"]["build"]["files"] + .as_object() + .ok_or("Desktop's main JavaScript directory is missing")?; + let mut found = None; + let mut read = 0_u64; + for (name, entry) in files { + if !name.starts_with("index") || !name.ends_with(".js") || entry["unpacked"] == true { + continue; + } + let size = entry["size"].as_u64().ok_or("invalid module size")?; + read = read.checked_add(size).ok_or("module sizes overflow")?; + if size > 16 * 1024 * 1024 || read > 64 * 1024 * 1024 { + return Err("Desktop's main JavaScript exceeds the inspection limit".into()); + } + let offset = entry["offset"] + .as_str() + .and_then(|s| s.parse::().ok()) + .and_then(|offset| start.checked_add(offset)) + .filter(|offset| offset.checked_add(size).is_some_and(|end| end <= length)) + .ok_or("invalid module offset")?; + archive + .seek(SeekFrom::Start(offset)) + .map_err(|e| e.to_string())?; + let mut source = vec![0; size as usize]; + archive.read_exact(&mut source).map_err(|e| e.to_string())?; + let source = std::str::from_utf8(&source).map_err(|e| e.to_string())?; + // shortcut: Desktop currently embeds literal JSON in JSON.parse; changed packaging needs a new reader. + for literal in source.split("JSON.parse('").skip(1) { + let Some(Ok(value)) = serde_json::Deserializer::from_str(literal) + .into_iter::() + .next() + else { + continue; + }; + let Some(runtime) = manifest(&value)? else { + continue; + }; + if found.is_some() { + return Err("Desktop's runtime manifest is ambiguous".into()); + } + found = Some(runtime); + } + } + found.ok_or_else(|| "Desktop's runtime manifest was not found".into()) +} + +fn manifest(value: &Value) -> Result, String> { + let manifest = &value["manifest"]; + let code_release = value["baseUrl"] + .as_str() + .and_then(|s| s.parse::().ok()) + .is_some_and(|uri| { + uri.path() + .split('/') + .any(|part| part == "claude-code-releases") + }); + if !code_release || !manifest["platforms"].is_object() { + return Ok(None); + } + let version = value["version"] + .as_str() + .ok_or("runtime version is missing")?; + if version.split('.').count() != 3 + || version.split('.').any(|part| { + part.is_empty() || part.len() > 6 || !part.bytes().all(|b| b.is_ascii_digit()) + }) + || manifest["version"] != version + { + return Err("invalid runtime version".into()); + } + let platform = match std::env::consts::ARCH { + "aarch64" => "darwin-arm64", + "x86_64" => "darwin-x64", + _ => return Err("unsupported macOS runtime architecture".into()), + }; + let checksum = manifest["platforms"][platform]["bundle"]["checksum"] + .as_str() + .filter(|s| { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) + }) + .ok_or("Desktop's managed bundle checksum is missing or invalid")?; + Ok(Some(Runtime { + version: version.into(), + checksum: checksum.into(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn inspect(header: Value, source: &[u8]) -> Result { + let header = header.to_string(); + let padding = (4 - header.len() % 4) % 4; + let header_size = header.len() + padding + 8; + let mut bytes = Vec::new(); + for number in [ + 4, + header_size as u32, + (header_size - 4) as u32, + header.len() as u32, + ] { + bytes.extend_from_slice(&number.to_le_bytes()); + } + bytes.extend_from_slice(header.as_bytes()); + bytes.resize(8 + header_size, 0); + bytes.extend_from_slice(source); + let path = std::env::temp_dir().join(format!( + "jaynshare-bundle-test-{}.asar", + uuid::Uuid::new_v4() + )); + std::fs::write(&path, bytes).unwrap(); + let result = runtime(&path); + std::fs::remove_file(path).unwrap(); + result + } + + #[test] + fn archive_offsets_sizes_and_manifest_ambiguity_are_checked() { + let value = json!({"version":"2.9.123", "baseUrl":"https://downloads.claude.ai/claude-code-releases", "manifest":{"version":"2.9.123", "platforms":{ + "darwin-arm64":{"bundle":{"checksum":"a".repeat(64)}}, + "darwin-x64":{"bundle":{"checksum":"a".repeat(64)}}}}}); + let source = format!("JSON.parse('{value}')"); + let mut header = json!({"files":{".vite":{"files":{"build":{"files":{"index.js":{"size":source.len(),"offset":"0"}}}}}}}); + assert_eq!( + inspect(header.clone(), source.as_bytes()).unwrap().version, + "2.9.123" + ); + let entry = &mut header["files"][".vite"]["files"]["build"]["files"]["index.js"]; + entry["offset"] = json!(u64::MAX.to_string()); + assert!( + inspect(header.clone(), source.as_bytes()) + .unwrap_err() + .contains("invalid module offset") + ); + let entry = &mut header["files"][".vite"]["files"]["build"]["files"]["index.js"]; + entry["offset"] = json!("0"); + entry["size"] = json!(u64::MAX); + assert!( + inspect(header.clone(), source.as_bytes()) + .unwrap_err() + .contains("inspection limit") + ); + header["files"][".vite"]["files"]["build"]["files"]["index.js"]["size"] = + json!(source.len()); + header["files"][".vite"]["files"]["build"]["files"]["index.chunk-other.js"] = + json!({"size":source.len(),"offset":source.len().to_string()}); + let duplicated = format!("{source}{source}"); + assert!( + inspect(header, duplicated.as_bytes()) + .unwrap_err() + .contains("ambiguous") + ); + } + + #[test] + fn validates_runtime_manifest_and_rejects_path_components() { + let mut value = json!({"version":"2.9.123", "baseUrl":"https://downloads.claude.ai/claude-code-releases", "manifest":{"version":"2.9.123", "platforms":{ + "darwin-arm64":{"bundle":{"checksum":"a".repeat(64)}}, + "darwin-x64":{"bundle":{"checksum":"a".repeat(64)}}}}}); + assert_eq!(manifest(&value).unwrap().unwrap().version, "2.9.123"); + value["version"] = json!("../../escape"); + assert!(manifest(&value).is_err()); + value["baseUrl"] = json!("https://downloads.claude.ai/claude-ssh-releases"); + assert!(manifest(&value).unwrap().is_none()); + assert!(manifest(&json!({"version":"1.0.0"})).unwrap().is_none()); + } +} diff --git a/src/desktop/compatibility.rs b/src/desktop/compatibility.rs new file mode 100644 index 0000000..ffc152b --- /dev/null +++ b/src/desktop/compatibility.rs @@ -0,0 +1,174 @@ +//! A bounded streaming exchange with the genuine runtime and a local mock. + +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use bytes::Bytes; +use http::{Method, Request, Response, StatusCode}; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::body::Incoming; +use hyper::service::service_fn; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use tokio::net::TcpListener; +use tokio::sync::oneshot; +use tokio::task::JoinSet; + +use super::probe; + +const MODEL: &str = "jaynshare-compatibility-check"; + +pub async fn check(runtime: &Path) -> Result<(), String> { + let scratch = + std::env::temp_dir().join(format!("jaynshare-desktop-check-{}", uuid::Uuid::new_v4())); + crate::state::ensure_private_dir(&scratch).map_err(|e| e.to_string())?; + let setup = async { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .map_err(|e| e.to_string())?; + let origin = format!( + "http://{}", + listener.local_addr().map_err(|e| e.to_string())? + ); + let key = uuid::Uuid::new_v4().to_string(); + let child = probe::command(runtime, &scratch, &origin, &key, MODEL) + .env("HTTP_PROXY", &origin) + .env("HTTPS_PROXY", &origin) + .env("NO_PROXY", "127.0.0.1,localhost") + .spawn() + .map_err(|e| e.to_string())?; + Ok::<_, String>((listener, key, child)) + } + .await; + let (listener, key, mut child) = match setup { + Ok(setup) => setup, + Err(why) => { + let _ = std::fs::remove_dir_all(&scratch); + return Err(format!("cannot start Desktop's local runtime check: {why}")); + } + }; + let (cancel, mut cancelled) = oneshot::channel::<()>(); + // The worker kills and reaps the child even when its caller disconnects. + let result = tokio::spawn(async move { + let mut connections = JoinSet::new(); + let seen = Arc::new(AtomicBool::new(false)); + let result = { + let collect = probe::collect(&mut child); + tokio::pin!(collect); + loop { + tokio::select! { + _ = &mut cancelled => break Err("runtime check cancelled".to_string()), + result = &mut collect => break result.map_err(|e| e.to_string()), + accepted = listener.accept() => { + let (socket, _) = match accepted { + Ok(pair) => pair, + Err(e) => break Err(e.to_string()), + }; + let key = key.clone(); + let seen = Arc::clone(&seen); + connections.spawn(async move { + let service = service_fn(move |request| mock(request, key.clone(), Arc::clone(&seen))); + let _ = hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(socket), service).await; + }); + } + _ = connections.join_next(), if !connections.is_empty() => {} + } + } + }; + let _ = child.kill().await; + connections.abort_all(); + while connections.join_next().await.is_some() {} + let _ = std::fs::remove_dir_all(&scratch); + match result { + Ok((bytes, success)) if success && seen.load(Ordering::Relaxed) => { + let result: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + if probe::healthy(&result) && result["result"] == "OK" { + return Ok(()); + } + } + Err(why) => return Err(format!("Desktop's managed runtime compatibility check failed: {why}")), + _ => {} + } + Err("Desktop's managed runtime did not pass the local streaming compatibility check; update Jaynshare for this Desktop build".into()) + }).await.map_err(|e| format!("Desktop's managed runtime check stopped: {e}"))?; + drop(cancel); + result +} + +async fn mock( + request: Request, + key: String, + seen: Arc, +) -> Result>, std::convert::Infallible> { + let reject = || { + Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Full::new(Bytes::new())) + .expect("empty response") + }; + if request.method() != Method::POST + || request.uri().scheme().is_some() + || request + .headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + != Some(format!("Bearer {key}").as_str()) + || !request + .headers() + .get("user-agent") + .is_some_and(|v| v.as_bytes().starts_with(b"claude-cli/")) + || request + .headers() + .get("x-claude-code-session-id") + .is_none_or(|v| v.as_bytes().is_empty()) + { + return Ok(reject()); + } + let (parts, body) = request.into_parts(); + let Ok(body) = Limited::new(body, 1024 * 1024).collect().await else { + return Ok(reject()); + }; + let Ok(decoded) = crate::data_plane::attempt::decode_body(&parts.headers, &body.to_bytes()) + else { + return Ok(reject()); + }; + let Ok(value) = serde_json::from_slice::(&decoded) else { + return Ok(reject()); + }; + if value["model"] != MODEL { + return Ok(reject()); + } + if parts.uri.path() == "/v1/messages/count_tokens" { + return Ok(Response::builder() + .header("content-type", "application/json") + .body(Full::new(Bytes::from_static(b"{\"input_tokens\":10}"))) + .expect("token count")); + } + if parts.uri.path() != "/v1/messages" || value["stream"] != true { + return Ok(reject()); + } + seen.store(true, Ordering::Relaxed); + let events = [ + json!({"type":"message_start", "message":{"id":"msg_local_check", "type":"message", "role":"assistant", "model":MODEL, "content":[], "stop_reason":null, "stop_sequence":null, "usage":{"input_tokens":10, "output_tokens":0}}}), + json!({"type":"content_block_start", "index":0, "content_block":{"type":"text", "text":""}}), + json!({"type":"content_block_delta", "index":0, "delta":{"type":"text_delta", "text":"OK"}}), + json!({"type":"content_block_stop", "index":0}), + json!({"type":"message_delta", "delta":{"stop_reason":"end_turn", "stop_sequence":null}, "usage":{"input_tokens":10, "output_tokens":1}}), + json!({"type":"message_stop"}), + ]; + let stream = events + .iter() + .map(|event| { + format!( + "event: {}\ndata: {event}\n\n", + event["type"].as_str().expect("event type") + ) + }) + .collect::(); + Ok(Response::builder() + .header("content-type", "text/event-stream") + .body(Full::new(Bytes::from(stream))) + .expect("stream response")) +} diff --git a/src/desktop/egress.rs b/src/desktop/egress.rs index 95d4e17..5c229be 100644 --- a/src/desktop/egress.rs +++ b/src/desktop/egress.rs @@ -1,5 +1,7 @@ //! Loopback forward proxy with the enrollment credential added only at the next hop. +use std::io::IsTerminal as _; +use std::path::Path; use std::sync::Arc; use std::time::Duration; @@ -34,31 +36,63 @@ pub async fn check_trust(installation: &client::ClientInstallation) -> Result<() let certificate = certificate.map_err(|_| "the enrolled CA bundle is invalid")?; let path = installation .directory - .join(format!("desktop-ca-check-{}.der", uuid::Uuid::new_v4())); - crate::state::write_private_atomic(&path, &certificate) + .join(format!("desktop-ca-check-{}.pem", uuid::Uuid::new_v4())); + let pem = crate::mitm::ca::pem("CERTIFICATE", &certificate); + crate::state::write_private_atomic(&path, pem.as_bytes()) .map_err(|e| format!("could not prepare the Desktop CA check: {e}"))?; - let verified = tokio::time::timeout( - Duration::from_secs(3), - tokio::process::Command::new("security") - .args(["verify-cert", "-L", "-l", "-c"]) - .arg(&path) - .kill_on_drop(true) - .output(), - ) - .await; + let result = trust_certificate(&path, &crate::mitm::ca::fingerprint(&certificate)).await; std::fs::remove_file(&path) .map_err(|e| format!("could not remove the Desktop CA check: {e}"))?; - if !matches!(verified, Ok(Ok(output)) if output.status.success()) { - return Err(format!( - "Desktop requires macOS trust for pool CA {}; `jaynshare trust-ca add` installs the current CA; also import and trust any staged CA from {} before relaunching Desktop", - crate::mitm::ca::fingerprint(&certificate), - ca_path.display() - )); - } + result?; } Ok(()) } +async fn trust_certificate(path: &Path, fingerprint: &str) -> Result<(), String> { + if trusted(path).await? { + return Ok(()); + } + if !std::io::stdin().is_terminal() { + return Err("installing the pool CA globally for Claude Desktop requires confirmation in a terminal".into()); + } + eprintln!("Pool CA fingerprint: {fingerprint}"); + eprintln!("This CA will be trusted by other applications using your macOS trust settings."); + let prompt = "Install CA globally (needed for Claude Desktop) [y/N] "; + let confirmed = crate::cli::confirm(prompt).map_err(|failure| { + failure.error["message"] + .as_str() + .unwrap_or("could not read the CA installation confirmation") + .to_string() + })?; + if !confirmed { + return Err( + "CA installation cancelled; Claude Desktop needs macOS trust for the pool CA".into(), + ); + } + crate::deploy::trust_store::add(path, fingerprint)?; + if !trusted(path).await? { + return Err(format!( + "macOS still does not trust pool CA {fingerprint} after installation" + )); + } + Ok(()) +} + +async fn trusted(path: &Path) -> Result { + let output = tokio::time::timeout( + Duration::from_secs(3), + tokio::process::Command::new("security") + .args(["verify-cert", "-L", "-l", "-c"]) + .arg(path) + .kill_on_drop(true) + .output(), + ) + .await + .map_err(|_| "checking macOS CA trust timed out")? + .map_err(|e| format!("could not check macOS CA trust: {e}"))?; + Ok(output.status.success()) +} + pub async fn handle( adapter: Arc, mut request: Request, diff --git a/src/desktop/mod.rs b/src/desktop/mod.rs index 126b239..b09eb9b 100644 --- a/src/desktop/mod.rs +++ b/src/desktop/mod.rs @@ -1,6 +1,8 @@ //! macOS Desktop Chat through a foreground native Gateway adapter. mod app; +mod bundle; +mod compatibility; mod config; mod egress; mod monitor; diff --git a/src/desktop/probe.rs b/src/desktop/probe.rs index d6f3e79..50c2c2a 100644 --- a/src/desktop/probe.rs +++ b/src/desktop/probe.rs @@ -7,7 +7,7 @@ use std::time::Duration; use http::{Response, StatusCode}; use serde_json::{Value, json}; use tokio::io::AsyncReadExt; -use tokio::process::Command; +use tokio::process::{Child, Command}; use tokio::sync::oneshot; use crate::data_plane::envelope::{json_response, proxy_response}; @@ -18,6 +18,77 @@ use super::{app::App, config::Integration}; const OUTPUT_LIMIT: u64 = 1024 * 1024; const DEADLINE: Duration = Duration::from_secs(9); +pub(super) fn command( + runtime: &Path, + scratch: &Path, + origin: &str, + key: &str, + model: &str, +) -> Command { + let mut command = Command::new(runtime); + // One argument, so a model ID can never be read as another option. + command + .args([ + "-p", + "Reply with exactly OK. Do not use tools.", + &format!("--model={model}"), + "--tools", + "", + "--setting-sources", + "", + "--strict-mcp-config", + "--mcp-config", + "{\"mcpServers\":{}}", + "--no-session-persistence", + "--output-format", + "json", + ]) + .current_dir(scratch) + .env_clear() + .env("HOME", scratch) + .env("TMPDIR", scratch) + .env("CLAUDE_CONFIG_DIR", scratch) + .env("PATH", "/usr/bin:/bin") + .env("LANG", "en_US.UTF-8") + .env("ANTHROPIC_BASE_URL", origin) + .env("ANTHROPIC_AUTH_TOKEN", key) + .env("ANTHROPIC_API_KEY", "") + .envs(crate::launch::env::CLAUDE_TELEMETRY_VARIABLES.map(|name| (name, "1"))) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + command +} + +pub(super) async fn collect(child: &mut Child) -> std::io::Result<(Vec, bool)> { + let stdout = child.stdout.take().expect("piped stdout"); + let mut stderr = child.stderr.take().expect("piped stderr"); + let read = async { + let mut bytes = Vec::new(); + stdout + .take(OUTPUT_LIMIT + 1) + .read_to_end(&mut bytes) + .await?; + if bytes.len() as u64 > OUTPUT_LIMIT { + return Err(std::io::Error::other("probe output exceeded its limit")); + } + Ok(bytes) + }; + let collect = async { + let mut sink = tokio::io::sink(); + let (bytes, _, status) = + tokio::try_join!(read, tokio::io::copy(&mut stderr, &mut sink), child.wait())?; + Ok((bytes, status.success())) + }; + tokio::time::timeout(DEADLINE, collect).await.map_err(|_| { + std::io::Error::new( + std::io::ErrorKind::TimedOut, + "Claude Code startup check exceeded 9 seconds", + ) + })? +} + pub async fn run( app: &App, integration: &Integration, @@ -46,40 +117,14 @@ pub async fn run( "could not prepare the isolated Desktop startup check", ); } - // One argument, so a model ID can never be read as another option. - let model_arg = format!("--model={model}"); - let child = Command::new(runtime) - .args([ - "-p", - "Reply with exactly OK. Do not use tools.", - &model_arg, - "--tools", - "", - "--setting-sources", - "", - "--strict-mcp-config", - "--mcp-config", - "{\"mcpServers\":{}}", - "--no-session-persistence", - "--output-format", - "json", - ]) - .current_dir(&scratch) - .env_clear() - .env("HOME", &scratch) - .env("TMPDIR", &scratch) - .env("CLAUDE_CONFIG_DIR", &scratch) - .env("PATH", "/usr/bin:/bin") - .env("LANG", "en_US.UTF-8") - .env("ANTHROPIC_BASE_URL", &integration.origin) - .env("ANTHROPIC_AUTH_TOKEN", &integration.key) - .env("ANTHROPIC_API_KEY", "") - .envs(crate::launch::env::CLAUDE_TELEMETRY_VARIABLES.map(|name| (name, "1"))) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .kill_on_drop(true) - .spawn(); + let child = command( + runtime, + &scratch, + &integration.origin, + &integration.key, + model, + ) + .spawn(); let Ok(mut child) = child else { let _ = std::fs::remove_dir_all(&scratch); return proxy_response( @@ -93,34 +138,15 @@ pub async fn run( let model = model.to_owned(); // The worker owns the child so dropping an HTTP request still kills AND reaps it. let worker = tokio::spawn(async move { - let stdout = child.stdout.take().expect("piped stdout"); - let mut stderr = child.stderr.take().expect("piped stderr"); - let read = async { - let mut bytes = Vec::new(); - stdout - .take(OUTPUT_LIMIT + 1) - .read_to_end(&mut bytes) - .await?; - if bytes.len() as u64 > OUTPUT_LIMIT { - return Err(std::io::Error::other("probe output exceeded its limit")); - } - Ok(bytes) - }; let completed = { - let collect = async { - let mut sink = tokio::io::sink(); - let (bytes, _, status) = - tokio::try_join!(read, tokio::io::copy(&mut stderr, &mut sink), child.wait())?; - Ok::<_, std::io::Error>((bytes, status.success())) - }; tokio::select! { _ = cancelled => None, - result = tokio::time::timeout(DEADLINE, collect) => Some(result), + result = collect(&mut child) => Some(result), } }; let response = match completed { - Some(Ok(Ok((bytes, success)))) => convert(&bytes, success, &model), - Some(Err(_)) => proxy_response( + Some(Ok((bytes, success))) => convert(&bytes, success, &model), + Some(Err(why)) if why.kind() == std::io::ErrorKind::TimedOut => proxy_response( StatusCode::GATEWAY_TIMEOUT, "timeout_error", "Claude Code startup check exceeded 9 seconds", @@ -154,16 +180,7 @@ pub async fn run( fn convert(bytes: &[u8], success: bool, model: &str) -> Response { let result: Value = serde_json::from_slice(bytes).unwrap_or(Value::Null); - if success - && result["type"] == "result" - && result["subtype"] == "success" - && result["is_error"] == false - && result["num_turns"] == 1 - && result["result"].as_str().is_some_and(|s| !s.is_empty()) - && result["stop_reason"] == "end_turn" - && result["usage"]["input_tokens"].as_u64().is_some() - && result["usage"]["output_tokens"].as_u64().is_some() - { + if success && healthy(&result) { return json_response( StatusCode::OK, &json!({ @@ -190,6 +207,17 @@ fn convert(bytes: &[u8], success: bool, model: &str) -> Response { ) } +pub(super) fn healthy(result: &Value) -> bool { + result["type"] == "result" + && result["subtype"] == "success" + && result["is_error"] == false + && result["num_turns"] == 1 + && result["result"].as_str().is_some_and(|s| !s.is_empty()) + && result["stop_reason"] == "end_turn" + && result["usage"]["input_tokens"].as_u64().is_some() + && result["usage"]["output_tokens"].as_u64().is_some() +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/desktop/transport.rs b/src/desktop/transport.rs index 03d4efb..117c217 100644 --- a/src/desktop/transport.rs +++ b/src/desktop/transport.rs @@ -228,6 +228,9 @@ impl Adapter { .headers .get(USER_AGENT) .is_some_and(|v| v.as_bytes().starts_with(b"claude-cli/")); + if engine && let Err(why) = self.app.runtime().await { + return error(StatusCode::SERVICE_UNAVAILABLE, &why); + } if !engine { if counting { return error( diff --git a/src/mitm/ca.rs b/src/mitm/ca.rs index bfddf14..9979134 100644 --- a/src/mitm/ca.rs +++ b/src/mitm/ca.rs @@ -532,7 +532,7 @@ fn remove_next(state_dir: &Path) -> Result<(), String> { } /// `der` as one PEM block. -fn pem(label: &str, der: &[u8]) -> String { +pub(crate) fn pem(label: &str, der: &[u8]) -> String { let body = base64::engine::general_purpose::STANDARD.encode(der); let mut out = format!("-----BEGIN {label}-----\n"); for line in body.as_bytes().chunks(64) { diff --git a/tests/acceptance/desktop.rs b/tests/acceptance/desktop.rs index f329e99..30fca93 100644 --- a/tests/acceptance/desktop.rs +++ b/tests/acceptance/desktop.rs @@ -122,19 +122,193 @@ mod macos { } #[tokio::test(flavor = "multi_thread")] - async fn untrusted_interception_ca_refuses_before_desktop_profile_setup() { + async fn untrusted_interception_ca_requires_terminal_confirmation_before_profile_setup() { let _leak_sweep = crate::leaks::LeakGuard::default(); let instance = Instance::start_client("desktop-egress-untrusted").await; instance.add_fsub(); let desktop = Desktop::new(&instance).await; fs::write(desktop.tools.dir.join("security/0000/exit"), "1").unwrap(); - let (code, _, error) = desktop.cli(&["desktop", "--auto"]); - assert_eq!(code, 1); - assert!(error.contains("trust-ca add")); + for args in [ + vec!["desktop", "--auto"], + vec!["--yes", "desktop", "--auto"], + ] { + let (code, _, error) = desktop.cli(&args); + assert_eq!(code, 1); + assert!(error.contains("confirmation in a terminal"), "{error}"); + } + assert!( + desktop + .tools + .calls("security") + .iter() + .all(|call| call[0] == "verify-cert") + ); + assert!(!desktop.record().exists()); + assert!(!desktop.profile.join("claude_desktop_config.json").exists()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn desktop_ca_installation_defaults_to_no() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let instance = Instance::start_client("desktop-ca-declined").await; + instance.add_fsub(); + let desktop = Desktop::new(&instance).await; + fs::write(desktop.tools.dir.join("security/0000/exit"), "1").unwrap(); + let tools = desktop.tools.env(); + let env: Vec<(&str, &str)> = tools + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + for answer in ["\n", "n\n"] { + let (code, transcript) = desktop.client.pty( + &["desktop", "--auto"], + &env, + &[( + "Install CA globally (needed for Claude Desktop) [y/N]", + answer, + )], + ); + assert_eq!(code, 1, "{transcript}"); + assert!( + transcript.contains("CA installation cancelled"), + "{transcript}" + ); + } + assert!( + desktop + .tools + .calls("security") + .iter() + .all(|call| call[0] == "verify-cert") + ); assert!(!desktop.record().exists()); assert!(!desktop.profile.join("claude_desktop_config.json").exists()); } + #[tokio::test(flavor = "multi_thread")] + async fn desktop_installs_the_confirmed_ca_and_continues_launching() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let instance = Instance::start_client("desktop-ca-confirmed").await; + instance.add_fsub(); + let desktop = Desktop::new(&instance).await; + fs::write(desktop.tools.dir.join("security/0000/exit"), "1").unwrap(); + fs::write(desktop.tools.dir.join("security/0000/times"), "1").unwrap(); + let installed = desktop.client.root.join("installed-ca.pem"); + let keychain = desktop + .client + .home + .join("Library/Keychains/login.keychain-db"); + desktop + .tools + .rule( + "security", + &[ + "add-trusted-cert", + "-r", + "trustRoot", + "-k", + keychain.to_str().unwrap(), + ], + ) + .run( + Path::new("/bin/cp"), + &["{argv}", installed.to_str().unwrap()], + ); + let tools = desktop.tools.env(); + let env: Vec<(&str, &str)> = tools + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + let (code, transcript) = desktop.client.pty( + &["desktop", "--auto", "--log"], + &env, + &[ + ( + "Install CA globally (needed for Claude Desktop) [y/N]", + "y\n", + ), + ("keep this command open", "\x03"), + ], + ); + assert_eq!(code, 0, "{transcript}"); + assert!(transcript.contains("other applications"), "{transcript}"); + assert_eq!( + fs::read_to_string(installed).unwrap(), + fs::read_to_string(desktop.client.client_dir.join("ca.pem")).unwrap() + ); + let calls = desktop.tools.calls("security"); + assert_eq!( + calls + .iter() + .map(|call| call[0].as_str()) + .collect::>(), + ["verify-cert", "add-trusted-cert", "verify-cert"] + ); + assert_eq!(calls[0][4], calls[1][5]); + assert_eq!(calls[0][4], calls[2][4]); + assert!(!Path::new(&calls[0][4]).exists()); + assert!(desktop.record().exists()); + let mut running = desktop.spawn(&["desktop", "--auto"]); + desktop.ready(&mut running).await; + assert!(!desktop.logs().contains("Install CA globally")); + assert_eq!( + desktop + .tools + .calls("security") + .iter() + .filter(|call| call[0] == "add-trusted-cert") + .count(), + 1 + ); + running.stop().await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn desktop_ca_installation_failures_prevent_profile_setup() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + for (status, error) in [ + (1, "installation denied"), + (0, "still does not trust pool CA"), + ] { + let instance = + Instance::start_client(&format!("desktop-ca-install-failure-{status}")).await; + instance.add_fsub(); + let desktop = Desktop::new(&instance).await; + fs::write(desktop.tools.dir.join("security/0000/match"), "verify-cert").unwrap(); + fs::write(desktop.tools.dir.join("security/0000/exit"), "1").unwrap(); + desktop + .tools + .rule("security", &["add-trusted-cert"]) + .exit(status) + .stderr("installation denied"); + let tools = desktop.tools.env(); + let env: Vec<(&str, &str)> = tools + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + let (code, transcript) = desktop.client.pty( + &["desktop", "--auto"], + &env, + &[( + "Install CA globally (needed for Claude Desktop) [y/N]", + "y\n", + )], + ); + assert_eq!(code, 1, "{transcript}"); + assert!(transcript.contains(error), "{transcript}"); + assert!(!desktop.record().exists()); + assert!(!desktop.profile.join("claude_desktop_config.json").exists()); + for call in desktop + .tools + .calls("security") + .iter() + .filter(|call| call[0] == "verify-cert") + { + assert!(!Path::new(&call[4]).exists()); + } + } + } + #[tokio::test(flavor = "multi_thread")] async fn desktop_refreshes_staged_roots_and_requires_trust_for_each() { let _leak_sweep = crate::leaks::LeakGuard::default(); @@ -158,7 +332,7 @@ mod macos { desktop.tools.rule("security", &[]).exit(1); let (code, _, error) = desktop.cli(&["desktop", "--auto"]); assert_eq!(code, 1); - assert!(error.contains("staged CA"), "{error}"); + assert!(error.contains("confirmation in a terminal"), "{error}"); assert_eq!( fs::read_to_string(&ca) .unwrap() @@ -178,6 +352,86 @@ mod macos { assert!(!desktop.record().exists()); } + #[tokio::test(flavor = "multi_thread")] + async fn desktop_installs_only_the_untrusted_staged_root() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let mut instance = Instance::start_client("desktop-ca-staged-confirmed").await; + instance.add_fsub(); + let desktop = Desktop::new(&instance).await; + let ca = desktop.client.client_dir.join("ca.pem"); + let current = fs::read_to_string(&ca).unwrap(); + assert_eq!( + instance.cli_json(&["ca", "rotate", "--yes"], None)["ok"], + true + ); + instance.restart(); + fs::write(desktop.tools.dir.join("security/0000/times"), "1").unwrap(); + desktop + .tools + .rule("security", &["verify-cert"]) + .times(1) + .exit(1); + let installed = desktop.client.root.join("installed-staged-ca.pem"); + let keychain = desktop + .client + .home + .join("Library/Keychains/login.keychain-db"); + desktop + .tools + .rule( + "security", + &[ + "add-trusted-cert", + "-r", + "trustRoot", + "-k", + keychain.to_str().unwrap(), + ], + ) + .run( + Path::new("/bin/cp"), + &["{argv}", installed.to_str().unwrap()], + ); + let tools = desktop.tools.env(); + let env: Vec<(&str, &str)> = tools + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + let (code, transcript) = desktop.client.pty( + &["desktop", "--auto", "--log"], + &env, + &[ + ( + "Install CA globally (needed for Claude Desktop) [y/N]", + "y\n", + ), + ("keep this command open", "\x03"), + ], + ); + assert_eq!(code, 0, "{transcript}"); + let bundle = fs::read_to_string(ca).unwrap(); + assert_eq!( + fs::read_to_string(installed).unwrap(), + bundle.strip_prefix(¤t).unwrap() + ); + assert_eq!( + desktop + .tools + .calls("security") + .iter() + .map(|call| call[0].as_str()) + .collect::>(), + [ + "verify-cert", + "verify-cert", + "add-trusted-cert", + "verify-cert" + ] + ); + assert_eq!(transcript.matches("Install CA globally").count(), 1); + assert!(desktop.record().exists()); + } + #[tokio::test(flavor = "multi_thread")] async fn proxy_requests_never_forward_the_local_gateway_bearer() { let _leak_sweep = crate::leaks::LeakGuard::default(); @@ -247,6 +501,32 @@ mod macos { serde_json::from_slice(&fs::read(path).expect("read JSON")).expect("JSON") } + fn app_archive(path: &Path, version: &str) { + let checksum = "a".repeat(64); + let manifest = json!({"version":version,"baseUrl":"https://downloads.claude.ai/claude-code-releases","manifest":{"version":version,"platforms":{ + "darwin-arm64":{"bundle":{"checksum":checksum}}, + "darwin-x64":{"bundle":{"checksum":checksum}}}}}); + let source = format!("function runtime(){{return JSON.parse('{manifest}')}}"); + let header = json!({"files":{".vite":{"files":{"build":{"files":{"index.js":{ + "size":source.len(),"offset":"0"}}}}}}}) + .to_string(); + let padding = (4 - header.len() % 4) % 4; + let header_size = header.len() + padding + 8; + let mut bytes = Vec::new(); + for number in [ + 4, + header_size as u32, + (header_size - 4) as u32, + header.len() as u32, + ] { + bytes.extend_from_slice(&number.to_le_bytes()); + } + bytes.extend_from_slice(header.as_bytes()); + bytes.resize(8 + header_size, 0); + bytes.extend_from_slice(source.as_bytes()); + fs::write(path, bytes).unwrap(); + } + impl Desktop { async fn new(instance: &Instance) -> Self { let client = install_client(instance).await; @@ -256,21 +536,54 @@ mod macos { let bundle = client.home.join("Applications/Claude.app/Contents"); fs::create_dir_all(bundle.join("Resources")).unwrap(); fs::write(bundle.join("Info.plist"), "CFBundleShortVersionString2.31226.0").unwrap(); - fs::write(bundle.join("Resources/app.asar"), "fixture app archive").unwrap(); + app_archive(&bundle.join("Resources/app.asar"), "2.1.293"); let tools = FakeTools::new(&client.root, &["open", "pgrep", "claude", "security"]); tools.rule("security", &[]).exit(0); tools.rule("pgrep", &[]).exit(1); tools .rule("claude", &["--version"]) .stdout("2.1.293 (Claude Code)\n"); - let managed = profile.join("claude-code/2.1.293/fixture-build"); + let managed = profile.join("claude-code/2.1.293/aaaaaaaaaaaa"); fs::create_dir_all(managed.join("claude.app/Contents/MacOS")).unwrap(); - fs::write(managed.join(".verified"), "verified fixture").unwrap(); + fs::write(managed.join(".verified"), "a".repeat(64)).unwrap(); let runtime = managed.join("claude.app/Contents/MacOS/claude"); let script = format!( - "#!/bin/sh\nif [ \"$1\" = --version ]; then FAKE_TOOL_DIR={} exec {} \"$@\"; fi\n/usr/bin/env > {}\nprintf '%s\\n' \"$@\" > {}\nprintf '%s' \"$$\" > {}\ncase \"$(/bin/cat {})\" in\nhang) exec /bin/sleep 30;;\nflood) exec /usr/bin/head -c 1048577 /dev/zero;;\nfail) /bin/cat {}; exit 1;;\n*) exec /bin/cat {};;\nesac\n", + r#"#!/bin/sh +if [ "$1" = --version ]; then FAKE_TOOL_DIR={} exec {} "$@"; fi +if [ "$3" = --model=jaynshare-compatibility-check ]; then + printf '%s\n' "$$" >> {} + case "$(/bin/cat {})" in + hang) exec /bin/sleep 30;; + flood) exec /usr/bin/head -c 1048577 /dev/zero;; + fail) exit 1;; + bad-auth) ANTHROPIC_AUTH_TOKEN=wrong;; + no-request) exec /bin/cat {};; + esac + /usr/bin/curl --silent --fail --max-time 3 --noproxy '*' \ + -H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" \ + -H 'User-Agent: claude-cli/2.1.293' \ + -H 'x-claude-code-session-id: synthetic-check' \ + -H 'content-type: application/json' \ + --data '{{"model":"jaynshare-compatibility-check","stream":true}}' \ + "$ANTHROPIC_BASE_URL/v1/messages" > /dev/null || exit 1 + exec /bin/cat {} +fi +/usr/bin/env > {} +printf '%s\n' "$@" > {} +printf '%s' "$$" > {} +case "$(/bin/cat {})" in + hang) exec /bin/sleep 30;; + flood) exec /usr/bin/head -c 1048577 /dev/zero;; + fail) /bin/cat {}; exit 1;; + *) exec /bin/cat {};; +esac +"#, quoted(&tools.dir), quoted(&tools.bin.join("claude")), + quoted(&client.root.join("compatibility-pids")), + quoted(&client.root.join("compatibility-mode")), + quoted(&client.root.join("compatibility-output")), + quoted(&client.root.join("compatibility-output")), quoted(&client.root.join("probe-env")), quoted(&client.root.join("probe-argv")), quoted(&client.root.join("probe-pid")), @@ -282,8 +595,14 @@ mod macos { use std::os::unix::fs::PermissionsExt; fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap(); fs::write(client.root.join("probe-mode"), "success").unwrap(); + fs::write(client.root.join("compatibility-mode"), "success").unwrap(); fs::write(client.root.join("probe-output"), json!({"type":"result", "subtype":"success", "is_error":false, "num_turns":1, "result":"OK", "stop_reason":"end_turn", "usage":{"input_tokens":17, "output_tokens":1}}).to_string()).unwrap(); + fs::copy( + client.root.join("probe-output"), + client.root.join("compatibility-output"), + ) + .unwrap(); crate::leaks::register_planted(&client.root.join("probe-env")); Self { client, @@ -1044,20 +1363,133 @@ mod macos { } #[tokio::test(flavor = "multi_thread")] - async fn version_runtime_and_managed_profile_changes_fail_before_setup() { + async fn future_desktop_and_runtime_versions_are_checked_without_an_allowlist() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let instance = Instance::start_client("desktop-future-version").await; + let desktop = Desktop::new(&instance).await; + let bundle = desktop.client.home.join("Applications/Claude.app/Contents"); + let plist = bundle.join("Info.plist"); + fs::write( + &plist, + fs::read_to_string(&plist) + .unwrap() + .replace("2.31226.0", "9.0.0"), + ) + .unwrap(); + app_archive(&bundle.join("Resources/app.asar"), "2.9.123"); + let original = desktop.runtime.ancestors().nth(5).unwrap(); + let current = desktop.profile.join("claude-code/2.9.123"); + fs::rename(original, ¤t).unwrap(); + for rule in fs::read_dir(desktop.tools.dir.join("claude")).unwrap() { + fs::write( + rule.unwrap().path().join("stdout"), + "2.9.123 (Claude Code)\n", + ) + .unwrap(); + } + // A different, verified build of the same version does not identify the active runtime. + let stale = current.join("bbbbbbbbbbbb"); + fs::create_dir_all(stale.join("claude.app/Contents/MacOS")).unwrap(); + fs::write(stale.join(".verified"), "b".repeat(64)).unwrap(); + fs::copy( + "/usr/bin/false", + stale.join("claude.app/Contents/MacOS/claude"), + ) + .unwrap(); + let mut running = desktop.spawn(&["desktop", "--auto"]); + let gateway = desktop.ready(&mut running).await; + for _ in 0..2 { + let answer = send(gateway.addr, gateway.authorize(messages(json!({"model": STARTUP_MODEL, "max_tokens": 1, "messages": [{"role":"user","content":"."}]})))).await; + assert_eq!(answer.status, StatusCode::OK); + } + assert_eq!( + fs::read_to_string(desktop.client.root.join("compatibility-pids")) + .unwrap() + .lines() + .count(), + 1 + ); + assert_eq!(instance.upstream.calls(), 0); + running.stop().await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn runtime_compatibility_failures_reject_setup_and_reap_children() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let instance = Instance::start_client("desktop-runtime-check-failures").await; + let desktop = Desktop::new(&instance).await; + for mode in ["fail", "no-request", "bad-auth", "flood", "hang"] { + fs::write(desktop.client.root.join("compatibility-mode"), mode).unwrap(); + let (code, _, error) = desktop.cli(&["desktop", "--auto"]); + assert_eq!(code, 1, "{mode}: {error}"); + assert!(error.contains("compatibility check"), "{mode}: {error}"); + assert!(!desktop.record().exists()); + assert!(!desktop.profile.join("claude_desktop_config.json").exists()); + let pid = fs::read_to_string(desktop.client.root.join("compatibility-pids")) + .unwrap() + .lines() + .last() + .unwrap() + .to_owned(); + assert!( + !Command::new("/bin/kill") + .args(["-0", &pid]) + .stderr(Stdio::null()) + .status() + .unwrap() + .success(), + "{mode}: child still running" + ); + } + fs::write(desktop.client.root.join("compatibility-mode"), "success").unwrap(); + fs::write( + desktop.client.root.join("compatibility-output"), + "invalid runtime JSON", + ) + .unwrap(); + assert_eq!(desktop.cli(&["desktop", "--auto"]).0, 1); + assert!(!desktop.record().exists()); + assert_eq!(instance.upstream.calls(), 0); + } + + #[tokio::test(flavor = "multi_thread")] + async fn mismatched_runtime_marker_refuses_before_setup() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let instance = Instance::start_client("desktop-runtime-marker").await; + let desktop = Desktop::new(&instance).await; + fs::write( + desktop + .runtime + .ancestors() + .nth(4) + .unwrap() + .join(".verified"), + "b".repeat(64), + ) + .unwrap(); + let (code, _, error) = desktop.cli(&["desktop", "--auto"]); + assert_eq!(code, 1); + assert!(error.contains("verification does not match"), "{error}"); + assert!(!desktop.record().exists()); + assert!(!desktop.client.root.join("compatibility-pids").exists()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn archive_runtime_and_managed_profile_changes_fail_before_setup() { let _leak_sweep = crate::leaks::LeakGuard::default(); let instance = Instance::start_client("desktop-compatibility").await; + instance.add_fsub(); let desktop = Desktop::new(&instance).await; - let plist = desktop + let archive = desktop .client .home - .join("Applications/Claude.app/Contents/Info.plist"); - let original = fs::read_to_string(&plist).unwrap(); - fs::write(&plist, original.replace("2.31226.0", "9.0.0")).unwrap(); + .join("Applications/Claude.app/Contents/Resources/app.asar"); + let original = fs::read(&archive).unwrap(); + fs::write(&archive, "invalid archive").unwrap(); assert_eq!(desktop.cli(&["desktop", "--auto"]).0, 1); assert!(!desktop.record().exists()); assert!(!desktop.profile.join("claude_desktop_config.json").exists()); - fs::write(&plist, original).unwrap(); + fs::write(&archive, original).unwrap(); let marker = desktop .runtime .ancestors() @@ -1067,11 +1499,33 @@ mod macos { fs::remove_file(&marker).unwrap(); let mut provisioning = desktop.spawn(&["desktop", "--auto"]); let gateway = desktop.ready(&mut provisioning).await; + let before = instance.upstream.calls(); let answer = send(gateway.addr, gateway.authorize(messages(json!({"model": STARTUP_MODEL, "max_tokens": 1, "messages": [{"role":"user","content":"."}]})))).await; assert_eq!(answer.status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + send(gateway.addr, gateway.engine("before-provisioning")) + .await + .status, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!(instance.upstream.calls(), before); + fs::write(&marker, "a".repeat(64)).unwrap(); + assert_eq!( + send(gateway.addr, gateway.engine("after-provisioning")) + .await + .status, + StatusCode::OK + ); + assert_eq!( + fs::read_to_string(desktop.client.root.join("compatibility-pids")) + .unwrap() + .lines() + .count(), + 1 + ); provisioning.stop().await; assert_eq!(desktop.cli(&["desktop", "--restore"]).0, 0); - fs::write(marker, "verified fixture").unwrap(); + fs::write(marker, "a".repeat(64)).unwrap(); let meta_path = desktop.profile.join("configLibrary/_meta.json"); write_private( &meta_path,