diff --git a/Cargo.toml b/Cargo.toml index 4435964..96994cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,10 @@ publish = false name = "baristore" path = "src/main.rs" +[[bin]] +name = "treenb-rootshell" +path = "src/treenb.rs" + [dependencies] # Only its I/O traits, channels and locks: the runtime is BariStore's own # (src/rt), on the one thread rootshell gives a WebAssembly program. diff --git a/src/app.rs b/src/app.rs index b3ecba9..67d7fa0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -669,7 +669,7 @@ impl App { let ask = self.asker(); let portal = portal::Portal { gs: &job.apple.0, account: &job.apple.1 }; job.shared = Some(install::shared(&portal, &job.team.id, &job.udid, &job.device_name, &job.session, - ask.as_ref()).await?); + ask.as_ref(), true).await?); } Ok(()) } @@ -694,7 +694,8 @@ impl App { ..Default::default() }; let reuse = replacing(&mut installed, reuse); - let done = self.sign_and_install(&mut job, ipa_path, opts, reuse, installed).await?; + let done = self.sign_and_install(&mut job, ipa_path, opts, reuse, installed, + install::Policy { inject_alt_certificate: true, ..Default::default() }).await?; Ok(done + &self.finish(&job).await) } @@ -711,15 +712,36 @@ impl App { icon_url: crate::icons::ipa_icon_url(path), ..Default::default() }; let reuse = replacing(&mut installed, reuse); - let done = self.sign_and_install(&mut job, path.to_path_buf(), opts, reuse, installed).await?; + let done = self.sign_and_install(&mut job, path.to_path_buf(), opts, reuse, installed, + install::Policy { inject_alt_certificate: true, ..Default::default() }).await?; + Ok(done + &self.finish(&job).await) + } + + pub async fn install_treenb(&self, path: &str) -> Result { + let path = std::path::Path::new(path); + if path.parent() != Some(state::path("ipas").as_path()) { + return Err("TreeNB package was not downloaded by this test engine.".into()); + } + self.step("Verifying the fixed TreeNB package"); + let main = crate::treenb_manifest::verify(path)?; + let mut job = self.job().await?; + let entry = Installed { + bundle_id: main.id.clone(), original_id: main.id.clone(), name: main.name.clone(), version: main.version.clone(), + ipa_path: path.to_string_lossy().into(), source_url: crate::treenb_manifest::version().url.into(), + icon_url: crate::icons::ipa_icon_url(path), ..Default::default() + }; + let policy = crate::treenb_manifest::policy(); + let done = self.sign_and_install(&mut job, path.to_path_buf(), Options::default(), + install::Reuse { pick: Some(main.id.clone()), ..Default::default() }, entry, policy).await?; Ok(done + &self.finish(&job).await) } async fn sign_and_install(&self, job: &mut Job, ipa: std::path::PathBuf, opts: Options, reuse: install::Reuse, - mut entry: Installed) -> Result { + mut entry: Installed, policy: install::Policy) -> Result { let ask = self.asker(); let previous = (!entry.bundle_id.is_empty()).then(|| (entry.bundle_id.clone(), entry.ids.clone())); let ctx = install::Context { + policy, gs: &job.apple.0, account: &job.apple.1, team: &job.team, udid: &job.udid, device_name: &job.device_name, session: &job.session, ask: ask.as_ref(), reuse, previous: previous.as_ref().map(|(id, ids)| (id.as_str(), ids)), @@ -934,7 +956,8 @@ impl App { entry.ipa_path = path.to_string_lossy().into(); } let opts = entry.signing_options(); - self.sign_and_install(job, entry.ipa_path.clone().into(), opts, install::Reuse::default(), entry).await + self.sign_and_install(job, entry.ipa_path.clone().into(), opts, install::Reuse::default(), entry, + install::Policy { inject_alt_certificate: true, ..Default::default() }).await } /// The catalog's offer for an installed app: the same app from the same @@ -982,7 +1005,8 @@ impl App { entry.version = v.version.clone(); entry.source_url = v.url.clone(); let opts = entry.signing_options(); - self.sign_and_install(job, entry.ipa_path.clone().into(), opts, install::Reuse::default(), entry).await?; + self.sign_and_install(job, entry.ipa_path.clone().into(), opts, install::Reuse::default(), entry, + install::Policy { inject_alt_certificate: true, ..Default::default() }).await?; Ok(format!("{name} is updated to {}.", v.version)) } @@ -1201,7 +1225,7 @@ impl App { let team = self.team()?; self.step("Loading the signing certificate"); let ask = self.asker(); - install::certificate(&portal::Portal { gs: &apple.0, account: &apple.1 }, &team.id, ask.as_ref()).await + install::certificate(&portal::Portal { gs: &apple.0, account: &apple.1 }, &team.id, ask.as_ref(), true).await } /// Options › Apple ID › Export certificate: the page shares the file, diff --git a/src/install.rs b/src/install.rs index fd1973d..a1a504e 100644 --- a/src/install.rs +++ b/src/install.rs @@ -180,9 +180,9 @@ fn now() -> u64 { /// Apps whose own code needs an app group (and reads ALTAppGroups), with the /// group id each looks up (behaviour as documented by nab138/isideload). -fn group_for(original_main: &str, team: &str, ipa: &Ipa) -> Option { +fn group_for(original_main: &str, team: &str, sidestore_inside: bool) -> Option { let base = original_main.trim_end_matches(".Beta"); - if base == "com.kdt.livecontainer" && has_sidestore_framework(ipa) { + if base == "com.kdt.livecontainer" && sidestore_inside { return Some(format!("group.com.SideStore.SideStore.{team}")); } if base == "com.SideStore.SideStore" || base == "com.rileytestut.AltStore" || base == "com.kdt.livecontainer" { @@ -191,6 +191,10 @@ fn group_for(original_main: &str, team: &str, ipa: &Ipa) -> Option { None } +fn selected_group(policy: &Policy, original_main: &str, team: &str, sidestore_inside: bool) -> Option { + policy.required_group.clone().or_else(|| group_for(original_main, team, sidestore_inside)) +} + pub fn new_identifier(original: &str, team: &str) -> String { if original.ends_with(&format!(".{team}")) { original.to_string() } else { format!("{original}.{team}") } } @@ -228,7 +232,27 @@ pub struct Reuse { pub extensions: bool, } +#[derive(Clone)] +pub struct Policy { + pub locked_main: Option, + pub required_group: Option, + pub inject_alt_certificate: bool, + pub allow_certificate_revocation: bool, +} + +impl Default for Policy { + fn default() -> Self { + Self { + locked_main: None, + required_group: None, + inject_alt_certificate: false, + allow_certificate_revocation: true, + } + } +} + pub struct Context<'a> { + pub policy: Policy, pub gs: &'a GrandSlam, pub account: &'a Account, pub team: &'a Team, @@ -251,10 +275,10 @@ pub struct Shared { } /// The four requests behind `Shared`, at the same time. -pub async fn shared(portal: &Portal<'_>, team: &str, udid: &str, device_name: &str, session: &Session, ask: &Asker) - -> Result +pub async fn shared(portal: &Portal<'_>, team: &str, udid: &str, device_name: &str, session: &Session, ask: &Asker, + allow_certificate_revocation: bool) -> Result { - let (cert, device, app_ids, on_device) = tokio::join!(certificate(portal, team, ask), + let (cert, device, app_ids, on_device) = tokio::join!(certificate(portal, team, ask, allow_certificate_revocation), portal.ensure_device(team, udid, device_name), portal.app_ids(team), device_ids(session)); device.map_err(|e| e.to_string())?; Ok(Shared { cert: cert?, app_ids: app_ids.map_err(|e| e.to_string())?, on_device: on_device? }) @@ -281,6 +305,19 @@ fn date(unix: u64) -> String { format!("{y}-{m:02}-{d:02}") } +fn selected_main_identifier(main: &bundle::Bundle, team: &str, previous: Option<(&str, &BTreeMap)>, + reuse: &Reuse, policy: &Policy) -> Result { + if let Some(locked) = &policy.locked_main { + if locked != &main.id { + return Err(format!("package identity mismatch: expected {locked}, found {}", main.id)); + } + return Ok(locked.clone()); + } + Ok(previous.map(|(id, ids)| ids.get(&main.dir).cloned().unwrap_or_else(|| id.to_string())) + .or_else(|| reuse.pick.clone()) + .unwrap_or_else(|| new_identifier(&main.id, team))) +} + /// The identifier each app/extension bundle gets: the previous install's, /// else the original with the team appended; extensions stay under the app. fn identifiers(apps: &[&bundle::Bundle], main: &bundle::Bundle, main_new: &str, @@ -299,6 +336,15 @@ fn identifiers(apps: &[&bundle::Bundle], main: &bundle::Bundle, main_new: &str, }).collect() } +fn selected_identifiers(apps: &[&bundle::Bundle], main: &bundle::Bundle, team: &str, + previous: Option<(&str, &BTreeMap)>, reuse: &Reuse, + policy: &Policy) -> Result<(String, BTreeMap), String> { + let main_new = selected_main_identifier(main, team, previous, reuse, policy)?; + let previous_ids = policy.locked_main.is_none().then(|| previous.map(|(_, ids)| ids)).flatten(); + let ids = identifiers(apps, main, &main_new, previous_ids); + Ok((main_new, ids)) +} + /// Makes the App IDs fit a free team's 10: when more are needed than are /// left, App IDs of apps no longer on the device are reused (asking first /// unless the settings say so). The app takes one whole; its extensions take @@ -326,6 +372,9 @@ async fn fit_app_ids(ctx: &Context<'_>, apps: &[&bundle::Bundle], main: &bundle: format!("Not enough App IDs: this app needs {}, {left} of {FREE_APP_IDS} are left.{when} \ Remove extensions needs fewer.", missing(ids)) }; + if ctx.policy.locked_main.is_some() { + return if has_room_for_locked_ids(ids, existing, ctx.team.free) { Ok(()) } else { Err(out_of_ids(ids)) }; + } if missing(ids) > left && !known(&ids[&main.dir]) { if free.is_empty() { return Err(out_of_ids(ids)); @@ -364,6 +413,12 @@ async fn fit_app_ids(ctx: &Context<'_>, apps: &[&bundle::Bundle], main: &bundle: Ok(()) } +fn has_room_for_locked_ids(ids: &BTreeMap, existing: &[AppId], free: bool) -> bool { + let left = if free { FREE_APP_IDS.saturating_sub(existing.len()) } else { usize::MAX }; + let missing = ids.values().filter(|id| !existing.iter().any(|a| &a.identifier == *id)).count(); + missing <= left +} + /// What the user answers to import a certificate instead of revoking one. pub const IMPORT_INSTEAD: &str = "Import that device's certificate instead"; @@ -371,8 +426,12 @@ pub const IMPORT_INSTEAD: &str = "Import that device's certificate instead"; /// the user picks one to revoke: nothing is revoked without asking (a /// BariStore certificate this device cannot sign with is most likely /// BariStore's on another device with the same Apple ID). -pub async fn certificate(portal: &Portal<'_>, team: &str, ask: &Asker) -> Result { +pub async fn certificate(portal: &Portal<'_>, team: &str, ask: &Asker, + allow_revocation: bool) -> Result { match portal.certificate(team).await { + Err(e) if e.code == portal::CERTS_FULL && !allow_revocation => { + Err("Apple 的开发证书已满。本测试安装器不会列出或吊销任何证书;请先在原设备导出并导入现有证书,或由证书所有者明确处理后再试。".into()) + } Err(e) if e.code == portal::CERTS_FULL => { let certs = portal.certificate_list(team).await.map_err(|e| e.to_string())?; let labels: Vec = certs.iter().map(|c| { @@ -422,7 +481,8 @@ pub async fn prepare_and_sign(ctx: &Context<'_>, shared: &mut Option, ip let portal = Portal { gs: ctx.gs, account: ctx.account }; let team = ctx.team.id.as_str(); if shared.is_none() { - *shared = Some(self::shared(&portal, team, ctx.udid, ctx.device_name, ctx.session, ctx.ask).await?); + *shared = Some(self::shared(&portal, team, ctx.udid, ctx.device_name, ctx.session, ctx.ask, + ctx.policy.allow_certificate_revocation).await?); } let shared = shared.as_mut().ok_or("no answer from Apple")?; let started = std::time::Instant::now(); @@ -447,12 +507,11 @@ pub async fn prepare_and_sign(ctx: &Context<'_>, shared: &mut Option, ip let bundles = ipa.bundles()?; let mut apps: Vec<&bundle::Bundle> = bundles.iter().filter(|b| b.kind != Kind::Framework).collect(); apps.sort_by_key(|b| b.depth()); - let mut main_new = ctx.previous.map(|(id, ids)| ids.get(&main.dir).cloned().unwrap_or_else(|| id.to_string())) - .or_else(|| ctx.reuse.pick.clone()) - .unwrap_or_else(|| new_identifier(&main.id, team)); - let mut ids = identifiers(&apps, &main, &main_new, ctx.previous.map(|(_, ids)| ids)); + let (mut main_new, mut ids) = selected_identifiers(&apps, &main, team, ctx.previous, &ctx.reuse, &ctx.policy)?; // A new App ID whose identifier exists: is an app installed under it? - if ctx.previous.is_none() && ctx.reuse.pick.is_none() && shared.app_ids.iter().any(|a| a.identifier == main_new) { + if ctx.policy.locked_main.is_none() && ctx.previous.is_none() && ctx.reuse.pick.is_none() + && shared.app_ids.iter().any(|a| a.identifier == main_new) + { let fresh = fresh_identifier(&main.id, team, &shared.on_device); if fresh != main_new { logf!("install: an app on the device is installed under {main_new}; {} gets {fresh}", main.name); @@ -491,7 +550,7 @@ pub async fn prepare_and_sign(ctx: &Context<'_>, shared: &mut Option, ip if !shared.on_device.contains(&ids[&main.dir]) { shared.on_device.push(ids[&main.dir].clone()); } - let group = group_for(&main.id, team, &ipa); + let group = selected_group(&ctx.policy, &main.id, team, has_sidestore_framework(&ipa)); let group_id = match &group { Some(group) => portal.group_id(team, group).await.map_err(|e| e.to_string())?, None => None, @@ -566,7 +625,11 @@ pub async fn prepare_and_sign(ctx: &Context<'_>, shared: &mut Option, ip if chain.is_empty() { return Err("the certificate Apple issued chains to an Apple CA BariStore does not know".into()); } - let add_files = alt_certificate(&bundles, &main, &cert, ctx.udid, &mut info_edits)?; + let add_files = if ctx.policy.inject_alt_certificate { + alt_certificate(&bundles, &main, &cert, ctx.udid, &mut info_edits)? + } else { + Vec::new() + }; let cert_serial_of_plan = cert.serial.clone(); let plan = Plan { identity: Identity { leaf, chain, key: cert.key, team: team.into(), common_name }, @@ -880,6 +943,67 @@ pub async fn install_signed(session: &Session, signed: &std::path::Path, entry: mod tests { use super::*; + fn test_bundle(dir: &str, id: &str, kind: Kind) -> bundle::Bundle { + bundle::Bundle { + dir: dir.into(), kind, id: id.into(), name: id.into(), version: "1".into(), + executable: "app".into(), info: Dictionary::new(), + } + } + + fn test_app_id(identifier: &str) -> AppId { + AppId { id: identifier.into(), identifier: identifier.into(), name: identifier.into(), + features: Default::default(), expires: 0 } + } + + #[test] + fn locked_treenb_identity_ignores_previous_team_ids() { + let main = test_bundle("Payload/TreeNB.app", "com.openssai.app", Kind::App); + let widget = test_bundle("Payload/TreeNB.app/PlugIns/AltWidgetExtension.appex", + "com.openssai.app.AltWidgetExtension", Kind::Extension); + let apps = [&main, &widget]; + let mut previous = BTreeMap::new(); + previous.insert(main.dir.clone(), "com.openssai.app.OLDTEAM".into()); + previous.insert(widget.dir.clone(), "com.openssai.app.OLDTEAM.WrongWidget".into()); + let policy = Policy { locked_main: Some("com.openssai.app".into()), ..Default::default() }; + let (main_id, ids) = selected_identifiers(&apps, &main, "NEWTEAM", Some(("com.openssai.app.OLDTEAM", &previous)), + &Reuse::default(), &policy).unwrap(); + assert_eq!(main_id, "com.openssai.app"); + assert_eq!(ids[&main.dir], "com.openssai.app"); + assert_eq!(ids[&widget.dir], "com.openssai.app.AltWidgetExtension"); + } + + #[test] + fn locked_identity_rejects_another_package() { + let main = test_bundle("Payload/Other.app", "com.example.other", Kind::App); + let policy = Policy { locked_main: Some("com.openssai.app".into()), ..Default::default() }; + let error = selected_identifiers(&[&main], &main, "TEAM", None, &Reuse::default(), &policy).unwrap_err(); + assert!(error.contains("package identity mismatch")); + } + + #[test] + fn treenb_group_is_explicit_and_certificate_injection_is_off() { + let policy = Policy { locked_main: Some("com.openssai.app".into()), + required_group: Some("group.com.openssai.app".into()), inject_alt_certificate: false, + allow_certificate_revocation: false }; + assert_eq!(selected_group(&policy, "com.openssai.app", "TEAM", true), Some("group.com.openssai.app".into())); + assert!(!policy.inject_alt_certificate); + assert_eq!(selected_group(&Policy::default(), "com.openssai.app", "TEAM", true), None); + } + + #[test] + fn locked_ids_fail_instead_of_reusing_an_unrelated_app_id() { + let mut ids = BTreeMap::new(); + ids.insert("main".into(), "com.openssai.app".into()); + ids.insert("widget".into(), "com.openssai.app.AltWidgetExtension".into()); + let mut existing = (0..9).map(|n| test_app_id(&format!("com.example.{n}"))).collect::>(); + assert!(!has_room_for_locked_ids(&ids, &existing, true)); + existing.push(test_app_id("com.openssai.app")); + assert!(!has_room_for_locked_ids(&ids, &existing, true)); + existing.push(test_app_id("com.openssai.app.AltWidgetExtension")); + assert!(has_room_for_locked_ids(&ids, &existing, true)); + assert!(has_room_for_locked_ids(&ids, &[], false)); + } + #[test] fn livecontainer_url_round_trips() { let p12 = [0xFBu8, 0xFF, 0xBF, 0x00, 0x3E]; diff --git a/src/log.rs b/src/log.rs index f170daa..a5bbb4e 100644 --- a/src/log.rs +++ b/src/log.rs @@ -39,6 +39,15 @@ pub fn stamp() -> String { /// The log file, kept open: each opening is a call to rootshell. static FILE: Mutex> = Mutex::new(None); +static FILE_ERROR: Mutex> = Mutex::new(None); + +fn set_file_error(message: String) { + *FILE_ERROR.lock().unwrap_or_else(|e| e.into_inner()) = Some(message); +} + +pub fn file_error() -> Option { + FILE_ERROR.lock().unwrap_or_else(|e| e.into_inner()).clone() +} pub fn line(text: impl AsRef) { let entry = format!("{} {}", stamp(), text.as_ref()); @@ -54,11 +63,18 @@ pub fn line(text: impl AsRef) { trim(&path); } if file.is_none() { - *file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); + match std::fs::OpenOptions::new().create(true).append(true).open(&path) { + Ok(opened) => { + *file = Some(opened); + *FILE_ERROR.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + Err(e) => set_file_error(format!("{}: {e}", path.display())), + } } if let Some(f) = file.as_mut() { - if f.write_all(format!("{entry}\n").as_bytes()).is_err() { + if let Err(e) = f.write_all(format!("{entry}\n").as_bytes()) { *file = None; + set_file_error(format!("{}: {e}", path.display())); } } recent.push(entry); diff --git a/src/main.rs b/src/main.rs index 17f85db..8084122 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ mod siphash; mod srp; mod state; mod store; +mod treenb_manifest; mod update; mod web; diff --git a/src/treenb.rs b/src/treenb.rs new file mode 100644 index 0000000..2b4fa0f --- /dev/null +++ b/src/treenb.rs @@ -0,0 +1,298 @@ +#![allow(dead_code, unused_imports)] + +mod app; +mod apple; +mod der; +mod device; +mod doctor; +mod http; +mod icons; +mod install; +mod log; +mod mdns; +mod net; +mod pairing; +mod rootshell; +mod rt; +mod sign; +mod siphash; +mod srp; +mod state; +mod store; +mod treenb_manifest; +mod update; +mod web; + +use std::process::ExitCode; +use std::sync::Mutex; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use serde_json::{json, Value as Json}; +use crate::app::App; +use crate::net::{TcpListener, TcpStream}; +use crate::rootshell::osc; + +#[cfg(target_arch = "wasm32")] +#[global_allocator] +static ALLOCATOR: rootshell::Nudging = rootshell::Nudging; + +const PAGE: &str = include_str!("../ui/treenb.html"); + +#[derive(serde::Serialize, serde::Deserialize)] +struct Running { boot: String, port: u16, key: String } + +fn running_path() -> std::path::PathBuf { state::path("treenb-live.json") } + +fn main() -> ExitCode { + let _ = rootshell::files::make_dirs(&state::home()); + let default_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + logf!("crash: {info}"); + default_hook(info); + })); + match rt::block_on(run()) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { eprintln!("treenb-rootshell: {e}"); ExitCode::FAILURE } + } +} + +async fn run() -> Result<(), String> { + #[cfg(target_arch = "wasm32")] + if !crate::rootshell::has_recv_timeouts() { + return Err("当前 RootShell 缺少所需的 WASI Runtime 能力。App Store 1.0.17-184 起已移除 WASM Runtime;请使用仍保留该能力的旧版、TestFlight 或其他构建。".into()); + } + if std::env::args().nth(1).as_deref() == Some("--join") { + if let Some(r) = running_instance().await? { + osc::open_url(&format!("http://127.0.0.1:{}/{}/", r.port, r.key)); + return Ok(()); + } + return Err("测试引擎没有运行。".into()); + } + if std::env::args().nth(1).as_deref() == Some("--version") { + osc::say("TreeNB RootShell test 0.1 (BariStore 1.2.3, TreeNB 1.4.8/202611292115)"); + return Ok(()); + } + if std::env::args().nth(1).as_deref() == Some("--check") { + return check(std::env::args().nth(2)).await; + } + let app = App::new(); + let listener = (45000..47000).find_map(|port| TcpListener::bind(port).ok()) + .ok_or("no free local port")?; + let port = listener.port(); + let key = hex::encode(rand::random::<[u8; 24]>()); + let running = Running { boot: app::boot_id().into(), port, key: key.clone() }; + state::write_private(&running_path(), serde_json::to_vec(&running).map_err(|e| e.to_string())?.as_slice()) + .map_err(|e| e.to_string())?; + osc::say("TreeNB RootShell 测试引擎已启动。"); + osc::say("若 Safari 没有自动打开,请保持 RootShell 在前并开启“允许程序打开链接”。"); + osc::open_url(&format!("http://127.0.0.1:{port}/{key}/")); + rt::spawn(idle_exit(app.clone())); + serve(app, listener, key, port).await; + Ok(()) +} + +fn valid_running(r: &Running) -> bool { + r.port != 0 && r.key.len() == 48 && r.key.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn ping_response(response: &[u8]) -> bool { + let Ok(text) = std::str::from_utf8(response) else { return false }; + let Some((head, body)) = text.split_once("\r\n\r\n") else { return false }; + head.starts_with("HTTP/1.1 200 OK\r\n") && body == "treenb-rootshell" +} + +async fn running_instance() -> Result, String> { + let Ok(bytes) = std::fs::read(running_path()) else { return Ok(None) }; + let Ok(r) = serde_json::from_slice::(&bytes) else { return Ok(None) }; + if !valid_running(&r) { + return Ok(None); + } + let request = format!("GET /{}/api/ping HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n\r\n", r.key, r.port); + let result = rt::time::timeout(Duration::from_secs(3), async { + let mut stream = TcpStream::connect("127.0.0.1", r.port).await.map_err(|e| e.to_string())?; + stream.write_all(request.as_bytes()).await.map_err(|e| e.to_string())?; + let mut response = Vec::new(); + let mut chunk = [0u8; 1024]; + while response.len() < 2048 { + let n = stream.read(&mut chunk).await.map_err(|e| e.to_string())?; + if n == 0 { break; } + response.extend_from_slice(&chunk[..n]); + } + Ok::<_, String>(response) + }).await; + let response = match result { + Ok(Ok(response)) => response, + _ => return Ok(None), + }; + if ping_response(&response) { Ok(Some(r)) } else { Ok(None) } +} + +async fn check(path: Option) -> Result<(), String> { + let path = path.ok_or("usage: treenb-rootshell --check TreeNB.ipa")?; + if path.starts_with("http://") || path.starts_with("https://") { + return Err("--check accepts a local IPA path; install downloads the fixed package itself.".into()); + } + treenb_manifest::verify(std::path::Path::new(&path))?; + osc::say("固定 TreeNB 1.4.8 包校验通过。未安装、未登录、未修改设备。"); + Ok(()) +} + +async fn idle_exit(app: App) { + let mut last = std::time::Instant::now(); + loop { + rt::time::sleep(Duration::from_secs(10)).await; + if app.busy() { last = std::time::Instant::now(); continue; } + let used = LAST_USE.lock().unwrap_or_else(|e| e.into_inner()).unwrap_or(last); + if used.elapsed() >= Duration::from_secs(240) { state::end(0); } + } +} + +static LAST_USE: Mutex> = Mutex::new(None); +fn used() { *LAST_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::time::Instant::now()); } + +async fn serve(app: App, listener: TcpListener, key: String, port: u16) { + loop { + let Ok(stream) = listener.accept().await else { continue }; + let (app, key, port) = (app.clone(), key.clone(), port); + rt::spawn(async move { let _ = handle(stream, app, &key, port).await; }); + } +} + +async fn respond(stream: &mut TcpStream, status: &str, kind: &str, body: &[u8]) -> std::io::Result<()> { + let head = format!("HTTP/1.1 {status}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'\r\nConnection: close\r\n\r\n", body.len()); + stream.write_all(head.as_bytes()).await?; + stream.write_all(body).await?; + stream.flush().await +} + +async fn read_some(stream: &mut TcpStream, buf: &mut [u8]) -> std::io::Result { + rt::time::timeout(Duration::from_secs(30), stream.read(buf)).await + .unwrap_or_else(|_| Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout"))) +} + +async fn handle(mut stream: TcpStream, app: App, key: &str, port: u16) -> std::io::Result<()> { + let mut head = Vec::new(); + let mut chunk = [0u8; 8192]; + let header_end = loop { + let n = read_some(&mut stream, &mut chunk).await?; + if n == 0 { return Ok(()); } + head.extend_from_slice(&chunk[..n]); + if let Some(p) = head.windows(4).position(|w| w == b"\r\n\r\n") { break p + 4; } + if head.len() > 64 * 1024 { return respond(&mut stream, "431 Too Large", "text/plain", b"").await; } + }; + let text = String::from_utf8_lossy(&head[..header_end]); + let mut lines = text.split("\r\n"); + let request = lines.next().unwrap_or(""); + let mut parts = request.split(' '); + let method = parts.next().unwrap_or(""); + let path = parts.next().unwrap_or(""); + let mut host = ""; + let mut origin = ""; + let mut length = 0usize; + for line in lines { + if let Some((k, v)) = line.split_once(':') { + match k.trim().to_ascii_lowercase().as_str() { + "host" => host = v.trim(), "origin" => origin = v.trim(), + "content-length" => length = v.trim().parse().unwrap_or(0), _ => {} + } + } + } + if host != format!("127.0.0.1:{port}") && host != format!("localhost:{port}") { + return respond(&mut stream, "403 Forbidden", "text/plain", b"").await; + } + let prefix = format!("/{key}"); + let route = match path.strip_prefix(&prefix) { Some(r) => r, None => return respond(&mut stream, "404 Not Found", "text/plain", b"").await }; + if method == "GET" && route == "/" { return respond(&mut stream, "200 OK", "text/html; charset=utf-8", PAGE.as_bytes()).await; } + if method == "GET" && route == "/api/ping" { + used(); + return respond(&mut stream, "200 OK", "text/plain", b"treenb-rootshell").await; + } + if method == "GET" && route == "/api/logs" { + used(); + let value = json!({"lines": log::recent(), "file_error": log::file_error(), + "home": state::home().to_string_lossy()}); + return respond(&mut stream, "200 OK", "application/json", value.to_string().as_bytes()).await; + } + if method == "GET" && route == "/api/state" { + let s = app.snapshot(); + let value = json!({"setup": s["setup"], "task": s["task"], "question": s["question"], + "pairing_code": s["pairing_code"], "pairing_waiting": s["pairing_waiting"], "busy": app.busy()}); + return respond(&mut stream, "200 OK", "application/json", value.to_string().as_bytes()).await; + } + if method != "POST" || route != "/api/action" { return respond(&mut stream, "404 Not Found", "text/plain", b"").await; } + if origin != format!("http://127.0.0.1:{port}{prefix}/") && origin != format!("http://localhost:{port}{prefix}/") { + return respond(&mut stream, "403 Forbidden", "text/plain", b"").await; + } + if length > 1 << 20 { return respond(&mut stream, "413 Too Large", "text/plain", b"").await; } + let mut body = head[header_end..].to_vec(); + while body.len() < length { + let n = read_some(&mut stream, &mut chunk).await?; + if n == 0 { break; } + body.extend_from_slice(&chunk[..n]); + } + used(); + let request: Json = serde_json::from_slice(&body).unwrap_or(Json::Null); + let reply = action(&app, &request).await; + respond(&mut stream, "200 OK", "application/json", reply.to_string().as_bytes()).await +} + +async fn action(app: &App, request: &Json) -> Json { + let kind = request.get("action").and_then(Json::as_str).unwrap_or(""); + if app.busy() { return json!({"ok": false, "message": "已有任务正在运行。"}); } + match kind { + "pair" => { let app = app.clone(); app.spawn("配对 TreeNB", None, move |app| async move { app.pair().await }); } + "login" => { + let email = request.get("email").and_then(Json::as_str).unwrap_or("").trim().to_string(); + let password = request.get("password").and_then(Json::as_str).unwrap_or("").to_string(); + if email.is_empty() || password.is_empty() { return json!({"ok": false, "message": "请输入 Apple ID 与密码。"}); } + let app = app.clone(); app.spawn("登录测试签名账号", None, move |app| async move { app.login(email, password).await }); + } + "install" => { + let app = app.clone(); app.spawn("安装 TreeNB 1.4.8", Some(json!({"action": "install"})), move |app| async move { + let v = treenb_manifest::version(); + app.step("下载固定 TreeNB 包"); + let progress = { let app = app.clone(); move |done: u64, total: u64| { + let pct = (done * 100 / total.max(1)) as u32; + app.progress(format!("下载 {:.1}/{:.1} MB", done as f64 / 1e6, total as f64 / 1e6), pct); + }}; + let path = store::download(&v, &progress).await?; + app.install_treenb(&path.to_string_lossy()).await + }); + } + "answer" => { + if let Some(id) = request.get("id").and_then(Json::as_u64) { + let value = request.get("value").and_then(Json::as_str).map(str::to_string); + app.answer(id, value); + } + } + _ => return json!({"ok": false, "message": "未知操作。"}) + } + json!({"ok": true}) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(port: u16, key: &str) -> Running { + Running { boot: "ignored".into(), port, key: key.into() } + } + + #[test] + fn join_requires_a_well_formed_record() { + assert!(valid_running(&record(45000, &"a".repeat(48)))); + assert!(!valid_running(&record(0, &"a".repeat(48)))); + assert!(!valid_running(&record(45000, &"a".repeat(47)))); + assert!(!valid_running(&record(45000, &"g".repeat(48)))); + } + + #[test] + fn join_requires_the_exact_ping_response() { + assert!(ping_response(b"HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\ntreenb-rootshell")); + assert!(!ping_response(b"HTTP/1.1 404 Not Found\r\n\r\ntreenb-rootshell")); + assert!(!ping_response(b"HTTP/1.1 200 OK\r\n\r\nother")); + assert!(!ping_response(b"HTTP/1.1 200 OK\r\n\r\ntreenb-rootshell\n")); + assert!(!ping_response(b"not http")); + } +} diff --git a/src/treenb_manifest.rs b/src/treenb_manifest.rs new file mode 100644 index 0000000..e714146 --- /dev/null +++ b/src/treenb_manifest.rs @@ -0,0 +1,99 @@ +use crate::{sign::bundle::{self, Bundle, Kind}, store::Version}; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::path::Path; + +pub fn version() -> Version { + Version { + source: "TreeNB".into(), source_url: "https://TreeNB.idoer.help".into(), channel: "test".into(), + version: "1.4.8".into(), date: "202611292115".into(), + url: "https://TreeNB.idoer.help/downloads/TreeNB-202611292115-unsigned.ipa".into(), + size: 21_030_483, + sha256: "244ff8c4713a9696824e1c68df56d507a4bdfe2dba976ad455ac39b41b73c3bf".into(), + min_os: "15.0".into(), notes: String::new(), warning: String::new(), + } +} + +pub fn policy() -> crate::install::Policy { + crate::install::Policy { + locked_main: Some("com.openssai.app".into()), + required_group: Some("group.com.openssai.app".into()), + inject_alt_certificate: false, + allow_certificate_revocation: false, + } +} + +pub fn verify(path: &Path) -> Result { + let mut file = std::fs::File::open(path).map_err(|e| e.to_string())?; + if file.metadata().map_err(|e| e.to_string())?.len() != version().size { + return Err("TreeNB package size does not match 1.4.8 (202611292115).".into()); + } + let mut hasher = Sha256::new(); + let mut pieces = [0u8; 256 * 1024]; + loop { + let n = file.read(&mut pieces).map_err(|e| e.to_string())?; + if n == 0 { break; } + hasher.update(&pieces[..n]); + crate::rt::check_in(); + } + if hex::encode(hasher.finalize()) != version().sha256 { + return Err("TreeNB package SHA-256 does not match the pinned 1.4.8 release.".into()); + } + let ipa = crate::rt::block_in_place(|| bundle::Ipa::read(path, &|_, _| {}))?; + let main = ipa.main_app()?; + if main.id != "com.openssai.app" || main.version != "1.0.261129" + || main.info.get("CFBundleVersion").and_then(plist::Value::as_string) != Some("202611292115") + || main.info.get("MinimumOSVersion").and_then(plist::Value::as_string) != Some("15.0") { + return Err("TreeNB main app identity, build, or minimum OS does not match the pinned release.".into()); + } + let extension = ipa.bundles()?.into_iter().find(|b| b.id == "com.openssai.app.AltWidgetExtension") + .ok_or("TreeNB widget extension is missing.")?; + if extension.kind != Kind::Extension { + return Err("TreeNB widget bundle is not an extension.".into()); + } + Ok(main) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pinned_manifest_is_complete() { + assert_eq!(version().size, 21_030_483); + assert_eq!(version().sha256.len(), 64); + assert_eq!(version().sha256, "244ff8c4713a9696824e1c68df56d507a4bdfe2dba976ad455ac39b41b73c3bf"); + } + + #[test] + fn treenb_policy_never_revokes_or_injects_a_certificate() { + let policy = policy(); + assert_eq!(policy.locked_main.as_deref(), Some("com.openssai.app")); + assert_eq!(policy.required_group.as_deref(), Some("group.com.openssai.app")); + assert!(!policy.inject_alt_certificate); + assert!(!policy.allow_certificate_revocation); + assert!(crate::install::Policy::default().allow_certificate_revocation); + } + + #[test] + fn missing_package_is_rejected() { + let path = crate::state::scratch("missing.ipa"); + assert!(verify(&path).unwrap_err().contains("No such file")); + } + + #[test] + #[ignore = "set TREENB_TEST_IPA to the pinned local release"] + fn verifies_real_release() { + let path = std::env::var_os("TREENB_TEST_IPA").expect("TREENB_TEST_IPA"); + let main = verify(Path::new(&path)).unwrap(); + assert_eq!(main.id, "com.openssai.app"); + assert_eq!(main.version, "1.0.261129"); + assert_eq!(main.info.get("CFBundleVersion").and_then(plist::Value::as_string), Some("202611292115")); + let mut changed = std::fs::read(Path::new(&path)).unwrap(); + changed[100] ^= 1; + let bad = crate::state::scratch("changed.ipa"); + std::fs::write(&bad, changed).unwrap(); + assert!(verify(&bad).unwrap_err().contains("SHA-256")); + let _ = std::fs::remove_file(bad); + } +} diff --git a/ui/treenb.html b/ui/treenb.html new file mode 100644 index 0000000..5fedfde --- /dev/null +++ b/ui/treenb.html @@ -0,0 +1,22 @@ + +TreeNB RootShell 测试 +
+
固定测试包 · 不接 TreeNB 更新链

TreeNB RootShell 测试

1.4.8 · build 202611292115 · iOS 15+

+
运行环境

仅支持仍保留 WASI Runtime 的 RootShell 构建;App Store 1.0.17-184 起已移除该能力。需连接 Wi-Fi、打开 LocalDevVPN、系统开发者模式与位置日记模式。

+
1
连接 Wi-Fi 与 LocalDevVPN

在系统开发者模式中允许配对;位置日记模式需开启,避免 RootShell 在 Safari 中暂停。

2
配对 iPhone

尚未配对

3
使用测试引擎登录 Apple ID

必须使用当前管理 com.openssai.app 及其 App ID 的 Apple ID 团队;其他团队无法续签这个固定身份。凭据只保存在本机 ~/.treenb-rootshell-test,不会写入 TreeNB 的账号、证书或更新存储。

+
覆盖安装 TreeNB

主 App、小组件与 App Group 身份均锁定。不会生成新的 App 身份,也不会向 TreeNB 注入重新导出的 p12。证书已满时直接停止,不列出、不吊销任何证书。

等待操作
+
固定包校验SHA-256
244ff8c4713a9696824e1c68df56d507a4bdfe2dba976ad455ac39b41b73c3bf

下载大小不符、哈希不符、身份错误或扩展缺失时,会在安装前停止。失败不会自动卸载或覆盖已有 App 数据。

+
诊断日志
正在读取引擎内存日志…
+ +