diff --git a/CHANGELOG.md b/CHANGELOG.md index c41c2dc10..93f26adc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ All notable changes to SideInstaller are documented here. +## 2.4.1 + +### Fixed +- **An Apple ID with a capital letter signs in.** Apple's sign-in proof is made from the email as + Apple keeps it, in lower case, so `Name@icloud.com`, as autofill or the Shift key types it, was + turned down as a wrong password. The email now goes to Apple in lower case wherever SideInstaller + signs in (installs, certificates, entitlements, Side by Side), and a sign-in saved under the + capitals keeps its session and signing key. +- **Every custom IPA stays** (#192, #194). Importing a custom IPA deleted the one before it, so + only the last custom app could be refreshed, from My apps or a Shortcut, and an app My apps + found by its IPA dropped out of the list. Each app now keeps its own: an import replaces only an + earlier one of the same app, and Settings › Downloaded IPAs lists them, to delete one by one. + Custom .ipa on the Install tab still installs the one imported last. +- **SideInstaller shows in My apps after installing itself** (#194). iOS closes SideInstaller as it + replaces it, which came before it noted the install; it now notes it first. +- **Apps that carry an Apple Watch app install.** The Watch app went along unsigned for your team, + still naming the app's old bundle ID, and such apps installed only once its folder was deleted + by hand. It's now left out, and so are the AppleDouble (`._`) files macOS adds to an IPA it zips. +- **Device IP is kept** (#198). One typed under Settings › Advanced, such as a reflector's over + Tailscale, went back to 10.7.0.1 at the next launch; it now stays until you change it. + ## 2.4.0 ### Added diff --git a/README.md b/README.md index ccd9d15b5..cc0865e2a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ **Install SideStore and LiveContainer directly on your iPhone. No PC required.** [![Install](https://img.shields.io/badge/Install-SideInstaller-2ea44f?style=for-the-badge)](https://sideinstaller.net/) -[![Version](https://img.shields.io/badge/version-2.4.0-2669ed?style=for-the-badge)](CHANGELOG.md) +[![Version](https://img.shields.io/badge/version-2.4.1-2669ed?style=for-the-badge)](CHANGELOG.md) [![Platform](https://img.shields.io/badge/platform-iOS-lightgrey?style=for-the-badge&logo=apple)](#requirements) [![License](https://img.shields.io/badge/license-Custom-orange?style=for-the-badge)](LICENSE.md) diff --git a/ios-app/AccountStore.swift b/ios-app/AccountStore.swift index 6278df71b..f7d0f0bc8 100644 --- a/ios-app/AccountStore.swift +++ b/ios-app/AccountStore.swift @@ -14,7 +14,8 @@ struct SavedAccount: Identifiable, Codable, Equatable { self.appleID = appleID } - /// The email as sent to Apple; a stray space breaks the SRP proof. + /// The email as typed, trimmed: a stray space breaks the SRP proof. + /// rust-core sends it to Apple in lower case (`apple_session::normalize_id`). var normalized: String { appleID.trimmingCharacters(in: .whitespacesAndNewlines) } diff --git a/ios-app/Engine.swift b/ios-app/Engine.swift index 1b5bbc3af..1393135ae 100644 --- a/ios-app/Engine.swift +++ b/ios-app/Engine.swift @@ -200,10 +200,22 @@ final class Engine { static let verboseLoggingKey = "verboseLogging" - // The loopback VPN's device-side IP; configurable in Advanced. - var deviceIP: String = Engine.defaultDeviceIP + // The loopback VPN's device-side IP; configurable in Advanced, and kept + // from one launch to the next (a reflector reached over Tailscale has its + // own: #198). The default isn't stored, so a later default applies. + var deviceIP: String = UserDefaults.standard.string(forKey: Engine.deviceIPKey) ?? Engine.defaultDeviceIP { + didSet { + let typed = deviceIP.trimmingCharacters(in: .whitespacesAndNewlines) + if typed.isEmpty || typed == Engine.defaultDeviceIP { + UserDefaults.standard.removeObject(forKey: Engine.deviceIPKey) + } else { + UserDefaults.standard.set(typed, forKey: Engine.deviceIPKey) + } + } + } /// Device IP's default: LocalDevVPN's far end of the tunnel. static let defaultDeviceIP = "10.7.0.1" + static let deviceIPKey = "deviceIP" /// `deviceIP` normalized to a dialable host, e.g. `10.7.0.1/32` → `10.7.0.1`. var deviceHost: String { NetworkStatus.host(deviceIP) } // Which build to install (SideStore, LiveContainer + SideStore, Madeira, or @@ -1106,7 +1118,8 @@ final class Engine { // MARK: Step 4 — Apple ID sign-in - /// The Apple ID as sent to Apple; a stray space breaks the SRP proof. + /// The Apple ID as typed, trimmed: a stray space breaks the SRP proof. + /// rust-core sends it to Apple in lower case (`apple_session::normalize_id`). var normalizedAppleID: String { appleID.trimmingCharacters(in: .whitespacesAndNewlines) } @@ -2205,6 +2218,14 @@ final class Engine { installProgress = 0 let ip = deviceHost let path = pairingFilePath ?? PairingController.pairingFilePath() + // So My apps can tell it from apps other tools installed. SideInstaller + // installing itself is noted first: iOS ends this process as it + // replaces the app, before anything after the install runs (#194). + let installed = signedAppBundleID() + let replacesItself = installed != nil && installed == Bundle.main.bundleIdentifier + if replacesItself, let installed { + InstalledAppsLedger.record(installed, flush: true) + } do { // iOS drops the idle tunnel during sign-in and signing, and // `isConnected` doesn't detect it, so reconnect first. Mobile Data @@ -2223,8 +2244,7 @@ final class Engine { throw EngineError.appLimit } installProgress = 1 - // So My apps can tell it from apps other tools installed. - if let installed = signedAppBundleID() { + if !replacesItself, let installed { InstalledAppsLedger.record(installed) } setStep(.install, .done) diff --git a/ios-app/MyAppsView.swift b/ios-app/MyAppsView.swift index 5b5bf1bac..5c4e29651 100644 --- a/ios-app/MyAppsView.swift +++ b/ios-app/MyAppsView.swift @@ -19,11 +19,14 @@ enum InstalledAppsLedger { Set(all(defaults).keys) } - /// Notes an app SideInstaller has just installed. - static func record(_ bundleID: String, defaults: UserDefaults = .standard) { + /// Notes an app SideInstaller has just installed. `flush` writes it out at + /// once, for when this process is about to end (SideInstaller replacing + /// itself). + static func record(_ bundleID: String, flush: Bool = false, defaults: UserDefaults = .standard) { var apps = all(defaults) apps[bundleID] = Date() defaults.set(apps, forKey: key) + if flush { defaults.synchronize() } } /// Forgets the apps that aren't among `onDevice` any more. diff --git a/ios-app/SideStoreDownloader.swift b/ios-app/SideStoreDownloader.swift index 1b0894f46..8280c9597 100644 --- a/ios-app/SideStoreDownloader.swift +++ b/ios-app/SideStoreDownloader.swift @@ -1820,8 +1820,8 @@ enum IPALibrary { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } - /// Folder for the imported custom IPA, separate so its name can't clash with - /// a download. + /// Folder for the imported custom IPAs, one per app (bundle ID), separate + /// so their names can't clash with a download. static var customDir: URL { documentsDir.appendingPathComponent("Custom", isDirectory: true) } @@ -1869,13 +1869,15 @@ enum IPALibrary { version: isManaged ? kind.source.version(inFileName: name, channel: kind.channel) : nil) } - return (entries + [customImport()].compactMap { $0 }) + return (entries + customImports()) .sorted { ($0.modified ?? .distantPast) > ($1.modified ?? .distantPast) } } - /// The imported IPA, if there is one; the newest wins if a stale one survives. - static func customImport() -> Entry? { - describe(namesIn: customDir) + /// Every imported IPA, newest first: one per app, so each custom app + /// installed keeps the IPA My apps and Shortcuts refresh it from (#192). + /// `dir` is for the tests. + static func customImports(in dir: URL = IPALibrary.customDir) -> [Entry] { + describe(namesIn: dir) .filter { $0.name.lowercased().hasSuffix(".ipa") } .map { (name, url, attrs) in Entry(source: .custom, channel: .stable, url: url, @@ -1883,7 +1885,12 @@ enum IPALibrary { modified: attrs[.modificationDate] as? Date, isImported: true, version: nil) } - .max { ($0.modified ?? .distantPast) < ($1.modified ?? .distantPast) } + .sorted { ($0.modified ?? .distantPast) > ($1.modified ?? .distantPast) } + } + + /// The IPA the Install tab installs as Custom: the one imported last. + static func customImport() -> Entry? { + customImports().first } /// Directory listing paired with each entry's attributes. @@ -1944,10 +1951,12 @@ enum IPALibrary { case notAnIPA } - /// Replaces the custom import with `url`, forcing a `.ipa` extension. - /// Blocking. Copies to a staging directory first, so only a complete, valid - /// IPA replaces the old one. The caller handles security-scoped access. - static func replaceCustomImport(with url: URL) throws -> URL { + /// Imports `url` as the custom IPA, forcing a `.ipa` extension: it replaces + /// an earlier import of the same app (bundle ID) or name, and the others + /// stay, so every custom app keeps its IPA. Blocking. Copies to a staging + /// directory first, so only a complete, valid IPA replaces the old one. The + /// caller handles security-scoped access. `dir` is for the tests. + static func replaceCustomImport(with url: URL, into dir: URL = IPALibrary.customDir) throws -> URL { let fm = FileManager.default let name = url.deletingPathExtension().lastPathComponent let staging = fm.temporaryDirectory @@ -1959,12 +1968,27 @@ enum IPALibrary { try copy(url, to: staged) guard looksLikeIPA(staged) else { throw ImportError.notAnIPA } - // One import at a time, so "the custom IPA" stays unambiguous. - try? fm.removeItem(at: customDir) - try fm.createDirectory(at: customDir, withIntermediateDirectories: true) - let dest = customDir.appendingPathComponent(name).appendingPathExtension("ipa") + try fm.createDirectory(at: dir, withIntermediateDirectories: true) + var dest = dir.appendingPathComponent(name).appendingPathExtension("ipa") + // An earlier import of the same app gives way to this one (one whose + // app can't be read, to one of the same name). + let app = appInfo(at: staged)?.bundleID + for old in customImports(in: dir) { + let same = app.map { appInfo(at: old.url)?.bundleID == $0 } + ?? (old.url.lastPathComponent == dest.lastPathComponent) + if same { try? fm.removeItem(at: old.url) } + } + // Another app's import of the same name stays: this one takes a free name. + var copyNumber = 2 + while fm.fileExists(atPath: dest.path) { + dest = dir.appendingPathComponent("\(name) \(copyNumber)").appendingPathExtension("ipa") + copyNumber += 1 + } // Same volume as the staging dir, so this is a rename, not a second copy. try fm.moveItem(at: staged, to: dest) + // A copy keeps the picked file's date; the Install tab's custom IPA is + // the newest, so this one is dated now. + try? fm.setAttributes([.modificationDate: Date()], ofItemAtPath: dest.path) return dest } diff --git a/ios-tests/MyAppsTests.swift b/ios-tests/MyAppsTests.swift index a250f8587..68c7b9040 100644 --- a/ios-tests/MyAppsTests.swift +++ b/ios-tests/MyAppsTests.swift @@ -64,4 +64,62 @@ struct MyAppsTests { #expect(InstalledAppsLedger.installed(defaults) == ["com.kdt.livecontainer.ABCDE12345"]) defaults.removePersistentDomain(forName: "MyAppsTests") } + + /// An IPA as far as IPALibrary reads one: a zip holding only + /// `Payload/App.app/Info.plist`, stored. + private func ipa(_ bundleID: String, named fileName: String, in dir: URL) throws -> URL { + let plist = try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier": bundleID], + format: .xml, options: 0) + let name = Data("Payload/App.app/Info.plist".utf8) + var archive = Data() + func put16(_ value: Int) { withUnsafeBytes(of: UInt16(value).littleEndian) { archive.append(contentsOf: $0) } } + func put32(_ value: Int) { withUnsafeBytes(of: UInt32(value).littleEndian) { archive.append(contentsOf: $0) } } + // Local header: version, flags, method (stored), time, date, CRC, sizes, name length, extra length. + put32(0x0403_4B50); put16(20); put16(0); put16(0); put16(0); put16(0) + put32(0); put32(plist.count); put32(plist.count); put16(name.count); put16(0) + archive.append(name); archive.append(plist) + // Central directory: as above, after "made by"; then comment, disk, + // attributes and the local header's offset. + let central = archive.count + put32(0x0201_4B50); put16(20); put16(20); put16(0); put16(0); put16(0); put16(0) + put32(0); put32(plist.count); put32(plist.count); put16(name.count); put16(0) + put16(0); put16(0); put16(0); put32(0); put32(0) + archive.append(name) + // End of central directory. + let centralLength = archive.count - central + put32(0x0605_4B50); put16(0); put16(0); put16(1); put16(1) + put32(centralLength); put32(central); put16(0) + let url = dir.appendingPathComponent(fileName) + try archive.write(to: url) + return url + } + + @Test("Every custom app keeps its IPA; a new one of the same app replaces it (#192)") + func customImports() throws { + let fm = FileManager.default + let scratch = fm.temporaryDirectory.appendingPathComponent("MyAppsTests-\(UUID().uuidString)") + let picked = scratch.appendingPathComponent("Picked") + let custom = scratch.appendingPathComponent("Custom") + try fm.createDirectory(at: picked, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: scratch) } + func kept() -> Set { Set(IPALibrary.customImports(in: custom).map(\.url.lastPathComponent)) } + + let liveContainer = try ipa("com.kdt.livecontainer", named: "LiveContainer.ipa", in: picked) + #expect(IPALibrary.appInfo(at: liveContainer)?.bundleID == "com.kdt.livecontainer") + _ = try IPALibrary.replaceCustomImport(with: liveContainer, into: custom) + _ = try IPALibrary.replaceCustomImport( + with: ipa("com.frizzle.SideInstaller", named: "SideInstaller.ipa", in: picked), into: custom) + #expect(kept() == ["LiveContainer.ipa", "SideInstaller.ipa"]) + + // A newer LiveContainer, whatever its name, takes the older one's place. + _ = try IPALibrary.replaceCustomImport( + with: ipa("com.kdt.livecontainer", named: "LiveContainer 3.8.1.ipa", in: picked), into: custom) + #expect(kept() == ["LiveContainer 3.8.1.ipa", "SideInstaller.ipa"]) + + // Another app under a name already taken: both stay. + let other = try IPALibrary.replaceCustomImport( + with: ipa("com.example.Other", named: "SideInstaller.ipa", in: picked), into: custom) + #expect(other.lastPathComponent == "SideInstaller 2.ipa") + #expect(kept() == ["LiveContainer 3.8.1.ipa", "SideInstaller.ipa", "SideInstaller 2.ipa"]) + } } diff --git a/rust-core/src/account.rs b/rust-core/src/account.rs index 7f8106816..d739afe07 100644 --- a/rust-core/src/account.rs +++ b/rust-core/src/account.rs @@ -282,11 +282,11 @@ pub unsafe fn apple_signin( out_summary: *mut *mut c_char, out_error: *mut *mut c_char, ) -> i32 { - let apple_id = opt(apple_id, ""); let password = opt(password, ""); let anisette_url = opt(anisette_url, "https://ani.sidestore.io"); let machine_name = opt(machine_name, "SideInstaller"); let storage_dir = opt(storage_dir, "."); + let apple_id = apple_session::normalized(Path::new(&storage_dir), &opt(apple_id, "")); let wanted = opt(team_id, "").trim().to_string(); let twofa = make_2fa(twofa_cb, TwoFaCtx(ctx)); let team_ctx = TwoFaCtx(ctx); diff --git a/rust-core/src/apple_session.rs b/rust-core/src/apple_session.rs index 80b3c726a..9cc7d0902 100644 --- a/rust-core/src/apple_session.rs +++ b/rust-core/src/apple_session.rs @@ -68,7 +68,7 @@ impl SavedSession { } fn usable_for(&self, apple_id: &str, now: u64) -> bool { - self.apple_id == apple_id + normalize_id(&self.apple_id) == normalize_id(apple_id) && self .expires_at() .is_none_or(|expires| now.saturating_add(EXPIRY_MARGIN_SECS) < expires) @@ -111,6 +111,33 @@ pub(crate) fn stated_expiry(expiry: u64) -> Option { } } +/// The Apple ID as Apple takes it: trimmed and in lower case. Apple's SRP proof +/// (M1) hashes the email, and Apple has it in lower case: one typed with a +/// capital, as iOS's keyboard starts it, was turned down as a wrong password, as +/// a stray space was. +pub(crate) fn normalize_id(apple_id: &str) -> String { + apple_id.trim().to_lowercase() +} + +/// `apple_id` normalized, for a sign-in that keeps its account in `storage_dir`. +/// The account's folder is named after the email (`account_dir`): one an +/// earlier SideInstaller made for it as typed, capitals and all, takes the +/// normalized name, so its session and signing key are kept. +pub(crate) fn normalized(storage_dir: &Path, apple_id: &str) -> String { + let id = normalize_id(apple_id); + let typed = apple_id.trim(); + if typed != id { + let (old, new) = (account_dir(storage_dir, typed), account_dir(storage_dir, &id)); + if old.is_dir() && !new.exists() { + match std::fs::rename(&old, &new) { + Ok(()) => tracing::info!("Apple ID: its folder goes by the email in lower case now"), + Err(e) => tracing::warn!("Apple ID: couldn't give its folder the email in lower case: {e}"), + } + } + } + id +} + /// An account's folder in isideload's storage, `/`, where /// isideload keeps its signing key as `key`. pub(crate) fn account_dir(storage_dir: &Path, apple_id: &str) -> PathBuf { @@ -140,9 +167,15 @@ fn store(storage_dir: &Path, session: &SavedSession) -> std::io::Result<()> { std::fs::rename(tmp, path) } -/// Drop an account's saved session. Returns whether there was one. +/// Drop an account's saved session, under the email in lower case and as typed +/// (one not signed in to since it was lower-cased). Returns whether there was +/// one. pub(crate) fn forget(storage_dir: &Path, apple_id: &str) -> bool { - std::fs::remove_file(session_path(storage_dir, apple_id)).is_ok() + let id = normalize_id(apple_id); + let typed = apple_id.trim(); + let lower = std::fs::remove_file(session_path(storage_dir, &id)).is_ok(); + let as_typed = typed != id && std::fs::remove_file(session_path(storage_dir, typed)).is_ok(); + lower || as_typed } /// What a full sign-in through an anisette server on Apple's Android ADI @@ -434,6 +467,32 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn the_apple_id_goes_in_lower_case_and_its_folder_with_it() { + assert_eq!(normalize_id(" Someone@Example.COM \n"), "someone@example.com"); + let dir = std::env::temp_dir().join(format!("si-session-case-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + // Saved by an earlier SideInstaller under the email as typed. + let mut session = saved(0, 0, NOW); + session.apple_id = "Someone@Example.com".into(); + store(&dir, &session).unwrap(); + std::fs::write(account_dir(&dir, "Someone@Example.com").join("key"), b"KEY").unwrap(); + assert_eq!(normalized(&dir, " Someone@Example.com "), "someone@example.com"); + assert!(!account_dir(&dir, "Someone@Example.com").exists()); + assert_eq!(std::fs::read(account_dir(&dir, "someone@example.com").join("key")).unwrap(), b"KEY"); + let moved = load(&dir, "someone@example.com").unwrap(); + assert!(moved.usable_for("someone@example.com", NOW)); + // Already lower case: nothing moves, and a folder there is never overwritten. + assert_eq!(normalized(&dir, "someone@example.com"), "someone@example.com"); + std::fs::create_dir_all(account_dir(&dir, "Someone@Example.com")).unwrap(); + assert_eq!(normalized(&dir, "Someone@Example.com"), "someone@example.com"); + assert!(account_dir(&dir, "Someone@Example.com").is_dir()); + // Forgotten under either name. + assert!(forget(&dir, "Someone@Example.com")); + assert!(load(&dir, "someone@example.com").is_none()); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn a_corrupt_file_reads_as_no_session() { let dir = std::env::temp_dir().join(format!("si-session-corrupt-{}", std::process::id())); diff --git a/rust-core/src/certs.rs b/rust-core/src/certs.rs index 0aaf96164..220c29027 100644 --- a/rust-core/src/certs.rs +++ b/rust-core/src/certs.rs @@ -119,10 +119,10 @@ pub unsafe fn cert_signin( out_summary: *mut *mut c_char, out_error: *mut *mut c_char, ) -> i32 { - let apple_id = opt_str(apple_id, ""); let password = opt_str(password, ""); let anisette_url = opt_str(anisette_url, "https://ani.sidestore.io"); let storage_dir = opt_str(storage_dir, "."); + let apple_id = apple_session::normalized(Path::new(&storage_dir), &opt_str(apple_id, "")); let wanted = opt_str(team_id, "").trim().to_string(); let twofa = make_2fa(twofa_cb, TwoFaCtx(ctx)); let team_ctx = TwoFaCtx(ctx); diff --git a/rust-core/vendor/isideload/README.md b/rust-core/vendor/isideload/README.md index cb4fb55a0..1e57ac190 100644 --- a/rust-core/vendor/isideload/README.md +++ b/rust-core/vendor/isideload/README.md @@ -812,6 +812,21 @@ an install on an iPhone, and whether iOS runs an ExtensionKit extension signed with the main app's profile and entitlements, the arrangement `PlugIns/` extensions get (changes 1 and 12). +**16. `src/sideload/application.rs` — leave out the Apple Watch app and +AppleDouble files.** + +`Bundle::new` collects `Frameworks/`, `PlugIns/` and `Extensions/`, never +`Watch/`, so an app carrying an Apple Watch app kept it as it came, signed by +someone else, and the install failed; on Discord (2026-12-01) the way round was +to unzip the IPA and delete `Watch/` by hand. `Application::new` now deletes +`Watch/` from the copy it extracts from an IPA, and every +AppleDouble file (`._name`, starting `00 05 16 07`) that macOS added when it +zipped the IPA: Nightflix's newest IPA has one beside its app, the only change +from the version that installs. A `._` file that isn't AppleDouble stays, and +an app given as a folder is left as it is. Tested by +`leaves_out_the_watch_app_and_apple_double_files`. Upstream `main` (`a0742ec`, +2026-12-03) still keeps `Watch/`. + ## Re-vendoring Upstream's `sign_app` and `install_app` take `increased_memory_limit: bool`, and diff --git a/rust-core/vendor/isideload/src/sideload/application.rs b/rust-core/vendor/isideload/src/sideload/application.rs index 76676d99f..f8fb6667d 100644 --- a/rust-core/vendor/isideload/src/sideload/application.rs +++ b/rust-core/vendor/isideload/src/sideload/application.rs @@ -12,7 +12,7 @@ use rootcause::option_ext::OptionExt; use rootcause::prelude::*; use sha2::{Digest, Sha256}; use std::fs::File; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use tokio::io::AsyncWriteExt; use tracing::{info, warn}; use zip::ZipArchive; @@ -25,6 +25,59 @@ pub struct Application { //pub temp_path: PathBuf, } +/// The first bytes of an AppleDouble file (`._name`), what macOS writes for a +/// file's extended attributes when it zips one. +const APPLE_DOUBLE: [u8; 4] = [0x00, 0x05, 0x16, 0x07]; + +/// Takes out of an extracted app what a sideloaded install can't carry or macOS +/// added: its Apple Watch app (`Watch/`, which `Bundle::new` doesn't sign, and +/// which still names the app's old bundle ID as its companion: installs of apps +/// with one went through only once it was deleted by hand) and AppleDouble +/// files. Only in the copy extracted from an IPA. +fn leave_out_extras(app: &Path) -> Result<(), Report> { + let watch = app.join("Watch"); + if watch.is_dir() { + std::fs::remove_dir_all(&watch).context("Failed to leave out the Apple Watch app")?; + info!("Left out the app's Apple Watch app"); + } + let removed = remove_apple_double(app); + if removed > 0 { + info!("Left out {removed} AppleDouble file(s) macOS added to the IPA"); + } + Ok(()) +} + +fn remove_apple_double(dir: &Path) -> usize { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + let mut removed = 0; + for entry in entries.flatten() { + let path = entry.path(); + match entry.file_type() { + Ok(t) if t.is_dir() => removed += remove_apple_double(&path), + Ok(t) if t.is_file() + && entry.file_name().to_string_lossy().starts_with("._") + && is_apple_double(&path) => + { + if std::fs::remove_file(&path).is_ok() { + removed += 1; + } + } + _ => {} + } + } + removed +} + +fn is_apple_double(path: &Path) -> bool { + let mut head = [0u8; 4]; + File::open(path) + .and_then(|mut f| std::io::Read::read_exact(&mut f, &mut head)) + .is_ok() + && head == APPLE_DOUBLE +} + impl Application { pub fn new(path: PathBuf) -> Result { if !path.exists() { @@ -68,6 +121,7 @@ impl Application { .collect(); if app_dirs.len() == 1 { bundle_path = app_dirs[0].path(); + leave_out_extras(&bundle_path)?; } else if app_dirs.is_empty() { bail!(SideloadError::InvalidBundle( "No .app directory found in Payload".to_string(), @@ -477,6 +531,47 @@ mod tests { plist::Value::Array(vec![GROUP.into()]) } + /// An IPA with an Apple Watch app and what macOS added (Nightflix's + /// newest has `Payload/._Nightflix.app` beside its app): the app alone is + /// signed, a `._` file that isn't AppleDouble kept. + #[test] + fn leaves_out_the_watch_app_and_apple_double_files() { + use std::io::Write; + let root = std::env::temp_dir().join(format!("isideload-extras-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&root).unwrap(); + let ipa = root.join("Extras.ipa"); + let mut zip = zip::ZipWriter::new(File::create(&ipa).unwrap()); + let info = |id: &str| { + let mut dict = plist::Dictionary::new(); + dict.insert("CFBundleIdentifier".into(), id.into()); + let mut out = Vec::new(); + plist::to_writer_xml(&mut out, &dict).unwrap(); + out + }; + let double = [&APPLE_DOUBLE[..], &[0, 2, 0, 0][..], &[0u8; 40][..]].concat(); + for (name, data) in [ + ("Payload/T.app/Info.plist", info("com.example.t")), + ("Payload/._T.app", double.clone()), + ("Payload/T.app/._Info.plist", double.clone()), + ("Payload/T.app/._keep", b"not AppleDouble".to_vec()), + ("__MACOSX/Payload/T.app/._Info.plist", double.clone()), + ("Payload/T.app/Watch/W.app/Info.plist", info("com.example.t.watchkitapp")), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(&data).unwrap(); + } + zip.finish().unwrap(); + + let app = Application::new(ipa.clone()).unwrap(); + let dir = app.bundle.bundle_dir.clone(); + assert_eq!(app.bundle.bundle_identifier(), Some("com.example.t")); + assert!(!dir.join("Watch").exists()); + assert!(!dir.join("._Info.plist").exists()); + assert!(dir.join("._keep").exists()); + let _ = std::fs::remove_dir_all(dir.parent().unwrap().parent().unwrap()); + let _ = std::fs::remove_dir_all(&root); + } + /// SideInstaller issue #110: the ExtensionKit extension in Extensions kept /// its bundle ID, which iOS refused as not under the app's new one. #[test]