diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f17a64..b675dc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ program it changes. To release, rename `[Unreleased]` to the version and date and raise the version in Cargo.toml, in the same pull request: once it is on main, the release is published with that section as its notes (AGENTS.md, Releasing). +## [Unreleased] + +### Installer and launcher + +- iPads and iPhones on iOS 12.0 to 13.7 can split their storage without DFU + mode: the installer offers Amethyst, signs its helper app with your Apple + ID through xtool and installs it. The device restarts once on the way; + open Orchard Installer again when it is back. It is the first choice on + those versions, ahead of checkra1n, and the only one on A12 and A13 + devices there. + +### Command line + +- `orchard install --access amethyst` takes the same route from the terminal. + ## [0.3.18] - 2026-12-05 ### Installer and launcher diff --git a/companion/App/App.swift b/companion/App/App.swift index 71afdc9..953144a 100644 --- a/companion/App/App.swift +++ b/companion/App/App.swift @@ -241,9 +241,13 @@ private func wide(_ view: UIView) { } /// Some devices restart their screen once before access; nothing can open the app again -/// then, and what that restart was for holds only about 20 seconds. -private func reopenNotice() -> UIView { - let text = label("If Orchard Installer doesn’t open again by itself, reopen it within 20 seconds.", sans(16, semibold: true), .rule, lineSpacing: 4) +/// then, and what that restart was for holds only about 20 seconds. In Amethyst (iOS 12 +/// and 13) the first run restarts the whole device instead, and the app is opened again +/// by hand (`restartsDevice`, resize-apfs's same notice). +private func reopenNotice(_ restartsDevice: Bool) -> UIView { + let line = restartsDevice ? "Your \(UIDevice.current.model) restarts once. Open Orchard Installer again when it’s back." + : "If Orchard Installer doesn’t open again by itself, reopen it within 20 seconds." + let text = label(line, sans(16, semibold: true), .rule, lineSpacing: 4) text.numberOfLines = 0 let content = row([icon("timer", 18), text], spacing: 14) let box = framed(content, UIColor.amber.withAlphaComponent(0.05), UIColor.amber.withAlphaComponent(0.32), vertical: 18, horizontal: 24) @@ -254,7 +258,7 @@ private func reopenNotice() -> UIView { /// Storage access (the app inside Dopamine, 9.1 and 9.2): with Continue, then with the /// spinner while access is obtained. -private func storageAccess(working: Bool, proceed: @escaping () -> Void) -> UIView { +private func storageAccess(working: Bool, restartsDevice: Bool, proceed: @escaping () -> Void) -> UIView { let steps = UIStackView(arrangedSubviews: ["The screen restarts and open apps close", "Unlock the device when it is back", "Orchard Installer opens again by itself"].map { row([icon("arrow-right", 18), label($0, sans(16), .rule)], spacing: 14) @@ -266,16 +270,16 @@ private func storageAccess(working: Bool, proceed: @escaping () -> Void) -> UIVi wide(steps) var views = [working ? badge(.accent, 0.08, fixed(Spinner(), 40, 40)) : badge(.accent, 0.12, icon("hard-drive", 38)), heading("Storage access", "Orchard Installer needs access to your device’s storage. This takes about a minute."), - steps, reopenNotice()] + steps, reopenNotice(restartsDevice)] if !working { views.append(ActionButton("Continue", action: proceed)) } return column(views) } /// 9.3. -private func accessFailed(retry: @escaping () -> Void) -> UIView { +private func accessFailed(restartsDevice: Bool, retry: @escaping () -> Void) -> UIView { column([badge(.red, 0.12, icon("x", 38)), heading("Couldn’t get storage access", "Your storage was not changed."), - reopenNotice(), ActionButton("Try again", action: retry)]) + reopenNotice(restartsDevice), ActionButton("Try again", action: retry)]) } /// Shows the screen for the helper's status, read every second. Inside the Dopamine app @@ -291,6 +295,8 @@ final class StatusController: UIViewController { refresh() } } + /// The device restarts once while access is obtained (Amethyst's first run). + var restartsDevice = false /// Continue and Try again on the Storage access page. var proceed: () -> Void = {} var retry: () -> Void = {} @@ -374,9 +380,9 @@ final class StatusController: UIViewController { content.subviews.forEach { $0.removeFromSuperview() } let view: UIView switch screen { - case "access": view = storageAccess(working: false) { [weak self] in self?.proceed() } - case "access-working": view = storageAccess(working: true) {} - case "access-failed": view = accessFailed { [weak self] in self?.retry() } + case "access": view = storageAccess(working: false, restartsDevice: restartsDevice) { [weak self] in self?.proceed() } + case "access-working": view = storageAccess(working: true, restartsDevice: restartsDevice) {} + case "access-failed": view = accessFailed(restartsDevice: restartsDevice) { [weak self] in self?.retry() } case "splitting": updateMinutes(); view = splitting(minutes: minutes) case "done": view = done() case "before": view = before(system: status?.system ?? "the system") diff --git a/companion/App/EmbeddedApp.swift b/companion/App/EmbeddedApp.swift index 1d44690..ab1d756 100644 --- a/companion/App/EmbeddedApp.swift +++ b/companion/App/EmbeddedApp.swift @@ -1,5 +1,7 @@ -// The companion inside the Dopamine app (no DFU): its settings for resize-apfs's shared -// access code (Access/StorageAccess.swift there) and its start. +// The companion inside the Dopamine app, or the Amethyst app on iOS 12 and 13 (no DFU): +// its settings for resize-apfs's shared access code (Access/StorageAccess.swift there) +// and its start. Amethyst's files live in the system's root, not /var/jb: StorageAccess +// moves the payload's path there by itself (`rooted(at:)`). import UIKit extension StorageAccess.Configuration { @@ -10,9 +12,16 @@ extension StorageAccess.Configuration { let given = Bundle.main.url(forResource: "helper-arguments", withExtension: "txt") .flatMap { try? String(contentsOf: $0, encoding: .utf8) }? .components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } ?? [] + // The Amethyst part (iOS 12.0 to 13.7) brings the Swift runtime its helper needs + // where iOS has none (12.0 and 12.1), as payloads; the helper looks for it here. + let runtime: [(resource: String, path: String)] = (Bundle.main.urls(forResourcesWithExtension: "payload", subdirectory: nil) ?? []) + .map { $0.deletingPathExtension().lastPathComponent } + .filter { $0.hasPrefix("libswift") && $0.hasSuffix(".dylib") } + .sorted() + .map { (resource: $0, path: "/var/jb/usr/libexec/orchard-companion/Frameworks/" + $0) } return StorageAccess.Configuration( name: "Orchard Installer", state: "OrchardCompanion", folder: folder, label: "org.orchardlinux.companion.embedded", - payloads: [("orchard-companion", "/var/jb/usr/libexec/orchard-companion/orchard-companion")], + payloads: [(resource: "orchard-companion", path: "/var/jb/usr/libexec/orchard-companion/orchard-companion")] + runtime, // The helper's status file and log are in the folder. arguments: ["--state-dir", folder] + given, lock: "/var/root/Library/OrchardCompanion/helper.lock", @@ -20,7 +29,8 @@ extension StorageAccess.Configuration { } } -/// Started by resize-apfs's Access/AccessBridge.m once the Dopamine app has launched. +/// Started by resize-apfs's Access/AccessBridge.m (Dopamine) or Access/AmethystBridge.m +/// (Amethyst) once the app has launched. @objc(RAFEmbeddedApp) final class EmbeddedApp: NSObject { private static var window: UIWindow? @@ -45,6 +55,7 @@ extension StorageAccess.Configuration { } } } + controller.restartsDevice = access.restartsDevice controller.proceed = { begin(.confirmed) } controller.retry = { begin(.retry) } let window = companionWindow(UIWindow(frame: UIScreen.main.bounds), controller) diff --git a/companion/build.sh b/companion/build.sh index 3adc700..cee7d16 100755 --- a/companion/build.sh +++ b/companion/build.sh @@ -6,6 +6,9 @@ # - out/access: what goes into the Dopamine app, so that one app is installed # without DFU. That is the app's interface as a library (iOS 15+, as # Dopamine), its Info.plist, its resources and the same helper as a payload. +# - out/access-ios12: the same for the Amethyst app (iOS 12.0 to 13.7), with +# Amethyst's executable built from its source (host/Amethyst) and the Swift +# runtime iOS 12.0 and 12.1 lack. # Needs Xcode's iOS SDK and ldid. # # From a resize-apfs checkout at the pinned commit (RESIZE_APFS, default @@ -27,7 +30,7 @@ if [ "${1:-}" = "--simulator" ]; then echo "Built $app" exit 0 fi -RESIZE_APFS_COMMIT=cd1f9db334af55104884aca77edfcd2a327140e2 +RESIZE_APFS_COMMIT=ade540a2dd457173d85e11e73cfe4293cc5b4696 resize=${RESIZE_APFS:-$PWD/../../worktrees/resize-shared-access} [ -d "$resize" ] || { echo "No resize-apfs checkout at $resize (set RESIZE_APFS)" >&2; exit 1; } resize=$(cd "$resize" && pwd) @@ -58,7 +61,7 @@ swiftc -parse-as-library -emit-library -static -emit-module -module-name ResizeD clang -c Helper/native.c -o "$work/native.o" swiftc -I "$work" -I "$resize/Sources/NativeSystem/include" -L "$work" -lResizeDevice -lResizeCore \ "$work/NativeSystem.o" "$work/native.o" -framework IOKit -framework CoreFoundation -framework MobileCoreServices \ - Helper/main.swift -o "$out/orchard-companion" + Helper/main.swift -Xlinker -rpath -Xlinker /usr/libexec/orchard-companion/Frameworks -o "$out/orchard-companion" # The entry program. clang Entry/entry.c -o "$out/orchard-companion-entry" @@ -77,10 +80,10 @@ xcrun ibtool --minimum-deployment-target 12.0 --target-device iphone --target-de --compile "$app/LaunchScreen.storyboardc" App/Launch/LaunchScreen.storyboard # Swift runtime: iOS 12.2 and later have it in /usr/lib/swift, searched first. -# iOS 12.0 and 12.1 don't; the checkra1n route's payload will bring Apple's -# back-deployment runtime in the app's Frameworks (as resize-apfs's -# scripts/build-device-ios12.sh does). Not here: palera1n needs iOS 15, and the -# runtime would add about 11 MB to the installer and every overlay. +# iOS 12.0 and 12.1 don't; only the Amethyst part below brings Apple's +# back-deployment runtime (palera1n needs iOS 15, and the overlays stay small). +# The helper also searches /usr/libexec/orchard-companion/Frameworks, where the +# Amethyst part puts it. # The app as the library the Dopamine app loads. AppDelegate.swift is the app's # start as a program of its own, which the library has no part in. @@ -115,5 +118,65 @@ ldid -SHelper/helper.entitlements.plist "$out/orchard-companion-entry" # the app with an Apple ID re-signs every program it finds, which would cost # the helper its own signature (StorageAccess takes the line off). { printf 'RESIZE-APFS-HELPER\n'; cat "$out/orchard-companion"; } > "$access/Resources/orchard-companion.payload" + +# The same for the Amethyst app (iOS 12.0 to 13.7, no DFU): the interface as a library +# for iOS 12 with resize-apfs's Access/AmethystBridge.m, the same Info.plist, resources +# and helper, and Amethyst's executable built from its source (resize-apfs's +# scripts/build-amethyst.sh: the official one is stripped of what the bridge calls). +access12="$out/access-ios12" +mkdir -p "$access12/host" +clang -fobjc-arc -fmodules -c "$resize/Access/AmethystBridge.m" -o "$work/AmethystBridge.o" +swiftc -parse-as-library -emit-library -module-name OrchardCompanion \ + "$resize/Access/StorageAccess.swift" App/App.swift App/EmbeddedApp.swift "$work/AmethystBridge.o" \ + -Xlinker -install_name -Xlinker @executable_path/Frameworks/OrchardCompanion.dylib \ + -Xlinker -rpath -Xlinker @executable_path/Frameworks \ + -o "$access12/OrchardCompanion.dylib" +for binary in "$access12/OrchardCompanion.dylib" "$out/orchard-companion"; do + first=$(xcrun otool -l "$binary" | awk '/cmd LC_RPATH/ {getline; getline; print $2; exit}') + [ "$first" = /usr/lib/swift ] || { echo "$binary must search /usr/lib/swift first, not $first" >&2; exit 1; } +done +xcrun --sdk iphoneos strip -x "$access12/OrchardCompanion.dylib" +codesign --force --sign - --timestamp=none "$access12/OrchardCompanion.dylib" +cp "$access/Info.plist" "$access12/Info.plist" +cp -R "$access/Resources" "$access12/Resources" +bash "$resize/scripts/build-amethyst.sh" "$access12/host/Amethyst" + +# Amethyst brings no Swift runtime, and iOS 12.0 and 12.1 have none (as resize-apfs's +# scripts/build-device-ios12.sh): Apple's back-deployment runtime comes along, each +# library the one that needs it: the interface's in Resources/Frameworks, which lands in +# the app's Frameworks; the helper's as payloads (signing with an Apple ID leaves them +# alone), which the app puts into /usr/libexec/orchard-companion/Frameworks +# (EmbeddedApp.swift). iOS 12.2 and later take their own from /usr/lib/swift, searched first. +runtime="$(dirname "$(dirname "$(xcrun --find swiftc)")")/lib/swift-5.0/iphoneos" +[ -f "$runtime/libswiftCore.dylib" ] || { echo "No Swift back-deployment runtime at $runtime" >&2; exit 1; } +rpath_libs() { xcrun otool -L "$1" | awk '/@rpath\/libswift.*\.dylib/ {sub("@rpath/", "", $1); print $1}'; } +strong_libs() { xcrun otool -l "$1" | awk '/cmd LC_LOAD_DYLIB/ {strong=1} /cmd LC_LOAD_WEAK_DYLIB/ {strong=0} /name @rpath\/libswift/ && strong {sub("@rpath/", "", $2); print $2}'; } +# The runtime libraries `binary` needs, with what they need themselves, into `folder`. +bundle_runtime() { + local binary=$1 folder=$2 pending next lib each + mkdir -p "$folder" + pending=$(rpath_libs "$binary" | sort -u) + while [ -n "$pending" ]; do + next="" + for lib in $pending; do + { [ -f "$folder/$lib" ] || [ ! -f "$runtime/$lib" ]; } && continue + # Bitcode is not used at runtime; Xcode strips it the same way when embedding. + xcrun bitcode_strip -r "$runtime/$lib" -o "$folder/$lib" + codesign --force --sign - --timestamp=none "$folder/$lib" + next+=" $(rpath_libs "$folder/$lib")" + done + pending=$(echo $next | tr ' ' '\n' | sort -u) + done + for each in "$binary" "$folder"/*.dylib; do + for lib in $(strong_libs "$each"); do + [ -f "$folder/$lib" ] || { echo "$each needs $lib, which iOS 12.0 lacks and which is not bundled" >&2; exit 1; } + done + done +} +bundle_runtime "$access12/OrchardCompanion.dylib" "$access12/Resources/Frameworks" +bundle_runtime "$out/orchard-companion" "$work/helper-runtime" +for lib in "$work"/helper-runtime/*.dylib; do + { printf 'RESIZE-APFS-HELPER\n'; cat "$lib"; } > "$access12/Resources/$(basename "$lib").payload" +done rm -rf "$work" echo "Built the companion in $out" diff --git a/crates/app/src/install_screens.rs b/crates/app/src/install_screens.rs index 0c84d3a..fbfc956 100644 --- a/crates/app/src/install_screens.rs +++ b/crates/app/src/install_screens.rs @@ -879,20 +879,30 @@ fn helper_failed(reason: &str, connected: bool, cx: &mut Context) -> } /// 7.8: the helper app is on the device; the rest is the user's there. -fn helper_steps(cx: &mut Context) -> Div { +/// `amethyst`: in Amethyst (iOS 12 and 13), which have no Developer Mode, +/// and where the device restarts once on the first run (tools#115). +fn helper_steps(amethyst: bool, cx: &mut Context) -> Div { const STEPS: &[Step] = &[ Step { parts: &[Part::Text("Turn on Developer Mode in Settings > Privacy & Security, if it isn't on yet. Your iPad restarts. Confirm Turn On.")], duration: None }, Step { parts: &[Part::Text("Trust your Apple ID in Settings > General > VPN & Device Management")], duration: None }, Step { parts: &[Part::Text("Open Orchard Installer and tap Continue")], duration: None }, ]; + const AMETHYST_STEPS: &[Step] = &[ + Step { parts: &[Part::Text("Trust your Apple ID in Settings > General > Profiles & Device Management")], duration: None }, + Step { parts: &[Part::Text("Open Orchard Installer and tap Continue")], duration: None }, + ]; // The app can get lost over the restarts on the way: once more, then. let again = pressable(crate::screens::link("install-again"), crate::screens::link_ring, cx, |this, _, _| this.send(Event::Retry)) .py(px(4.)) .child(div().text_size(px(14.)).text_color(c(MUTED)).child("Install the app again")); - let note = div().w_full().text_size(px(13.)).line_height(px(19.)).text_color(c(AMBER)).child("The screen restarts once after step 3. If Orchard Installer doesn't open again by itself, reopen it within 20 seconds."); + let (note, steps) = match amethyst { + true => (orchard_flow::for_device("Your iPad restarts once. Open Orchard Installer again when it's back."), AMETHYST_STEPS), + false => ("The screen restarts once after step 3. If Orchard Installer doesn't open again by itself, reopen it within 20 seconds.", STEPS), + }; + let note = div().w_full().text_size(px(13.)).line_height(px(19.)).text_color(c(AMBER)).child(note); column() .child(header("Set up the helper app", orchard_flow::for_device("Orchard Installer is now on your iPad. Do these steps there. This window moves on as soon as it's ready."), TITLE)) - .child(div().w_full().flex().flex_col().gap(px(16.)).child(note).child(steps_natural(STEPS))) + .child(div().w_full().flex().flex_col().gap(px(16.)).child(note).child(steps_natural(steps))) .child(div().flex().flex_row().mt(px(-20.)).child(again)) } @@ -1365,7 +1375,7 @@ pub fn text_column(installer: &mut Installer, cx: &mut Context) -> Op let connected = matches!(installer.flow.at, Some((_, orchard_flow::UsbMode::Normal))); helper_failed(reason, connected, cx).into_any_element() } - State::HelperSteps { .. } => helper_steps(cx).into_any_element(), + State::HelperSteps { .. } => helper_steps(installer.flow.helper() == Some(orchard_flow::Helper::Amethyst), cx).into_any_element(), State::WaitPwned { device, failed, restarting, .. } => wait_pwned(device, *failed, *restarting, cx).into_any_element(), State::ChooseSplit { layout, omarchy_gb, approved, .. } => { installer.layout = Some(layout.clone()); diff --git a/crates/app/src/screens.rs b/crates/app/src/screens.rs index f3500c4..d672de6 100644 --- a/crates/app/src/screens.rs +++ b/crates/app/src/screens.rs @@ -945,7 +945,12 @@ fn options_dialog(installer: &Installer, focus: &gpui::FocusHandle, cx: &mut Con let mut greyed = Vec::new(); let (label, explanation): (&str, String) = match kind_of { OptionsFor::Helper => { - for (at, (id, text, helper)) in [("helper-dopamine", "Dopamine", Helper::Dopamine), ("helper-palera1n", "palera1n", Helper::Palera1n), ("helper-checkra1n", "checkra1n", Helper::Checkra1n)].into_iter().enumerate() { + for (at, (id, text, helper)) in [ + ("helper-dopamine", "Dopamine", Helper::Dopamine), + ("helper-amethyst", "Amethyst", Helper::Amethyst), + ("helper-palera1n", "palera1n", Helper::Palera1n), + ("helper-checkra1n", "checkra1n", Helper::Checkra1n), + ].into_iter().enumerate() { let choice = view.helpers.iter().find(|c| c.value == helper).copied(); let (selected, available) = choice.map_or((false, false), |c| (c.selected, c.available)); if !available { @@ -955,6 +960,8 @@ fn options_dialog(installer: &Installer, focus: &gpui::FocusHandle, cx: &mut Con } let line = match view.helpers.iter().find(|c| c.selected).map(|c| c.value) { Some(Helper::Dopamine) => format!("Jailbreaks your {name} without a restart."), + // tools#115: the device restarts once on Amethyst's first run. + Some(Helper::Amethyst) => format!("Jailbreaks your {name} without DFU mode. Your {name} restarts once."), Some(_) => format!("Restarts your {name} via DFU mode into a temporary jailbreak."), None => String::new(), }; diff --git a/crates/cli/src/commands/install.rs b/crates/cli/src/commands/install.rs index 14802b2..1aca9b4 100644 --- a/crates/cli/src/commands/install.rs +++ b/crates/cli/src/commands/install.rs @@ -92,19 +92,20 @@ pub struct InstallArgs { /// ORCHARD_BUSY_CPU=1) #[arg(long)] pub busy_cpu: bool, - /// How iPadOS is entered to resize it (palera1n, checkra1n, dopamine); - /// otherwise the first that fits the device + /// How iPadOS is entered to resize it (palera1n, checkra1n, dopamine, + /// amethyst); otherwise the first that fits the device #[arg(long, value_name = "ROUTE", value_parser = ACCESS_ROUTES)] pub access: Option, /// The iPadOS or iOS version on the device, where it can't say (DFU and /// recovery mode): 14, 15.8, ...; asked when not given #[arg(long, value_name = "VERSION")] pub ios: Option, - /// dopamine: the Apple ID that signs the helper app; asked when needed + /// dopamine, amethyst: the Apple ID that signs the helper app; asked + /// when needed #[arg(long, value_name = "ID")] pub apple_id: Option, - /// dopamine: the Apple ID's password: a file, or - for the first line of - /// stdin; asked when needed + /// dopamine, amethyst: the Apple ID's password: a file, or - for the + /// first line of stdin; asked when needed #[arg(long, value_name = "FILE")] pub apple_password_file: Option, #[command(flatten)] @@ -151,7 +152,7 @@ pub struct ToolFlags { /// The access routes `install --access` runs: each has its helper in /// [`access_helper`]. A route the board data names but this list lacks is /// refused when the command line is read, never run as another one. -const ACCESS_ROUTES: [&str; 3] = ["palera1n", "checkra1n", "dopamine"]; +const ACCESS_ROUTES: [&str; 4] = ["palera1n", "checkra1n", "dopamine", "amethyst"]; /// The helper of an access route, by its name; None for one this version /// does not run. @@ -161,10 +162,31 @@ fn access_helper(route: &str) -> Option { "palera1n" => Some(Helper::Palera1n), "checkra1n" => Some(Helper::Checkra1n), "dopamine" => Some(Helper::Dopamine), + "amethyst" => Some(Helper::Amethyst), _ => None, } } +/// What the user does on the device once the helper app is on it, and the +/// note under it. Amethyst's iOS 12 and 13 have no Developer Mode, and its +/// first run restarts the device once (tools#115). +fn helper_steps(helper: Option) -> (&'static [&'static str], &'static str) { + if helper == Some(orchard_flow::Helper::Amethyst) { + return ( + &["Trust your Apple ID in Settings > General > Profiles & Device Management", "Open Orchard Installer and tap Continue"], + "Your iPad restarts once. Open Orchard Installer again when it's back.", + ); + } + ( + &[ + "Turn on Developer Mode in Settings > Privacy & Security, if it isn't on yet. Your iPad restarts. Confirm Turn On.", + "Trust your Apple ID in Settings > General > VPN & Device Management", + "Open Orchard Installer and tap Continue", + ], + "The screen restarts once after step 3. If Orchard Installer doesn't open again by itself, reopen it within 20 seconds.", + ) +} + /// The flow's Options from the flags; None when none of them was given, so /// the environment's switches count as before. fn flow_options(access: Option<&str>, tool: &ToolFlags, busy_cpu: bool) -> Result, String> { @@ -1733,20 +1755,16 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode { } State::HelperSteps { .. } => { if first { - const STEPS: [&str; 3] = [ - "Turn on Developer Mode in Settings > Privacy & Security, if it isn't on yet. Your iPad restarts. Confirm Turn On.", - "Trust your Apple ID in Settings > General > VPN & Device Management", - "Open Orchard Installer and tap Continue", - ]; + let (steps, note) = helper_steps(flow.helper()); out.term.live(None); - out.event(json!({"event": "needs", "action": "helper-steps", "steps": STEPS.iter().map(|t| orchard_flow::for_device(t)).collect::>()})); + out.event(json!({"event": "needs", "action": "helper-steps", "steps": steps.iter().map(|t| orchard_flow::for_device(t)).collect::>()})); out.term.blank(); out.heading("Set up the helper app", None); out.sub(orchard_flow::for_device("Orchard Installer is now on your iPad. Do these steps there.")); - for (i, step) in STEPS.iter().enumerate() { + for (i, step) in steps.iter().enumerate() { out.term.line(vec![s(format!(" {} ", i + 1), MUTED), s(orchard_flow::for_device(step), FG)]); } - out.term.line(vec![s(" The screen restarts once after step 3. If Orchard Installer doesn't open again by itself, reopen it within 20 seconds.", YELLOW)]); + out.term.line(vec![s(format!(" {}", orchard_flow::for_device(note)), YELLOW)]); shared.offer_retry(&mut out, "install the app again"); out.term.live_restart(vec![s("Waiting for the helper app", SUB)]); } @@ -2782,10 +2800,26 @@ mod tests { helpers.push(helper); assert_eq!(flow_options(Some(route), &tool, false).unwrap().unwrap().helper, Some(helper)); } - let refused = flow_options(Some("amethyst"), &tool, false).unwrap_err(); - assert!(refused.contains("does not run the amethyst access route"), "{refused}"); + let refused = flow_options(Some("unknown"), &tool, false).unwrap_err(); + assert!(refused.contains("does not run the unknown access route"), "{refused}"); use clap::Parser; - assert!(crate::args::Cli::try_parse_from(["orchard", "install", "--access", "amethyst"]).is_err()); + assert!(crate::args::Cli::try_parse_from(["orchard", "install", "--access", "unknown"]).is_err()); + } + + /// `install --access amethyst` takes the Amethyst helper app, and its + /// steps on the device are Amethyst's: no Developer Mode, one restart. + #[test] + fn install_takes_the_amethyst_route() { + use clap::Parser; + let parsed = crate::args::Cli::try_parse_from(["orchard", "install", "--access", "amethyst"]).map(|cli| cli.command); + let Ok(crate::args::Command::Install(args)) = parsed else { panic!("--access amethyst does not parse") }; + assert_eq!(args.access.as_deref(), Some("amethyst")); + let tool = ToolFlags { palera1n_version: None, port_reset: None }; + assert_eq!(flow_options(Some("amethyst"), &tool, false).unwrap().unwrap().helper, Some(orchard_flow::Helper::Amethyst)); + let (steps, note) = helper_steps(Some(orchard_flow::Helper::Amethyst)); + assert!(!steps.iter().any(|s| s.contains("Developer Mode"))); + assert_eq!(note, "Your iPad restarts once. Open Orchard Installer again when it's back."); + assert!(helper_steps(Some(orchard_flow::Helper::Dopamine)).0[0].contains("Developer Mode")); } #[test] diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index a9964ef..6cc945c 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -97,6 +97,16 @@ pub enum Helper { Palera1n, Checkra1n, Dopamine, + /// As Dopamine, with the Amethyst app (where it fits: the data's routes). + Amethyst, +} + +impl Helper { + /// Whether the helper is an app signed and installed on the device + /// while iOS runs (Dopamine, Amethyst), with no round into DFU mode. + pub fn is_app(self) -> bool { + matches!(self, Helper::Dopamine | Helper::Amethyst) + } } /// What takes a device from DFU mode to a loader that starts Linux. @@ -433,7 +443,7 @@ pub enum State { // Prepare: split the storage in iPadOS /// The restart out of recovery mode, for a helper that needs iOS running. Restarting { device: Device, slow: bool }, - /// The helper app is signed and installed (Dopamine): the first try + /// The helper app is signed and installed (Dopamine, Amethyst): the first try /// finds out whether an Apple sign-in is needed. HelperInstalling { device: Device }, HelperSignIn { device: Device, apple_id: String, password: String, problem: Option, busy: bool }, @@ -616,7 +626,7 @@ pub enum Event { EntryStarted, /// A command to the device in recovery mode didn't go through, with why. RecoveryFailed(String), - // The helper app (Dopamine) + // The helper app (Dopamine, Amethyst) /// Signing the helper app needs an Apple sign-in first. HelperNeedsSignIn, /// The helper app is on the device (it may have been there, still valid). @@ -992,7 +1002,7 @@ pub fn start_stage(lines: &[String]) -> Option<&'static str> { "Checkmate · waiting for the iPad on USB" } else if l.contains("Setting up the exploit") || l.contains("setup stage") || l.contains("UaF race") || l.contains("checkm8") { "Setting up the exploit" - } else if l.contains("Fetching Dopamine") || l.contains("Fetching xtool") { + } else if l.contains("Fetching Dopamine") || l.contains("Fetching Amethyst") || l.contains("Fetching xtool") { "Fetching the app" } else if l.contains("Putting the app into it") { "Preparing the helper app" @@ -1091,11 +1101,11 @@ fn step_inner(app: App, mut flow: Flow, event: Event) -> (Flow, Vec) { } Event::SetOptions(ref options) => { flow.options = options.clone(); - // Dopamine, chosen during a round into DFU mode for the split, - // ends that round (update_plain); any other choice waits for - // the next step. + // A helper app (Dopamine, Amethyst), chosen during a round into + // DFU mode for the split, ends that round (update_plain); any + // other choice waits for the next step. let leaves_round = matches!(&flow.state, State::DfuAgain { device, why: Again::Prepare | Again::RetryPrepare, .. } - if rules::helper(&flow.options, device) == Some(Helper::Dopamine)); + if rules::helper(&flow.options, device).is_some_and(Helper::is_app)); if !leaves_round { return (flow, out); } @@ -1759,7 +1769,7 @@ fn update_plain(app: App, ctx: &Ctx, state: State, event: Event) -> (State, Vec< (S::Restarting { device, .. }, E::Timeout) => (S::Restarting { device, slow: true }, none()), (S::Restarting { device, slow: true }, E::Retry) => start_over(device, ctx.at), - // ---- The helper app (Dopamine) ---- + // ---- The helper app (Dopamine, Amethyst) ---- (S::HelperInstalling { device }, E::HelperNeedsSignIn) => { (S::HelperSignIn { device, apple_id: String::new(), password: String::new(), problem: None, busy: false }, none()) } @@ -1855,11 +1865,11 @@ fn update_plain(app: App, ctx: &Ctx, state: State, event: Event) -> (State, Vec< (_, E::SplitRunning { device, omarchy_gb }) => (S::Splitting { device, omarchy_gb, link: Link::Lost, reopened: true }, none()), // ---- A round into DFU mode ---- - // Dopamine chosen in its Options (palera1n's start didn't work, say): - // the helper app needs iOS, not DFU mode. The device is found again - // as it is, and Continue takes the app. + // A helper app chosen in its Options (palera1n's start didn't work, + // say): it needs iOS, not DFU mode. The device is found again as it + // is, and Continue takes the app. (S::DfuAgain { device, why: Again::Prepare | Again::RetryPrepare, .. }, E::SetOptions(_)) - if rules::helper(&ctx.options, &device) == Some(Helper::Dopamine) => + if rules::helper(&ctx.options, &device).is_some_and(Helper::is_app) => { start_over(device, ctx.at) } @@ -1939,7 +1949,7 @@ fn update_plain(app: App, ctx: &Ctx, state: State, event: Event) -> (State, Vec< // Back to the split, by the helper it takes. The device has to leave // the install system first. (S::NotPrepared { device }, E::Continue) => { - if rules::helper(&ctx.options, &device) == Some(Helper::Dopamine) { + if rules::helper(&ctx.options, &device).is_some_and(Helper::is_app) { let mode = ctx.at.unwrap_or(UsbMode::Install); return (S::Found { device, mode, confirm_skip: false, restart: true }, none()); } @@ -2079,13 +2089,13 @@ fn go_on(app: App, ctx: &Ctx, device: Device, mode: UsbMode) -> (State, Vec stay(device), - (UsbMode::Normal, Some(Helper::Dopamine)) => helper_setup(device), + (UsbMode::Normal, Some(h)) if h.is_app() => helper_setup(device), // Out of recovery mode the installer restarts the device itself. - (UsbMode::Recovery, Some(Helper::Dopamine)) => { + (UsbMode::Recovery, Some(h)) if h.is_app() => { (State::Restarting { device, slow: false }, vec![Effect::PrepareRecovery(id.clone()), Effect::RestartFromRecovery(id)]) } // Out of DFU mode it can't: the user restarts it. - (_, Some(Helper::Dopamine)) => (State::Found { device, mode, confirm_skip: false, restart: true }, Vec::new()), + (_, Some(h)) if h.is_app() => (State::Found { device, mode, confirm_skip: false, restart: true }, Vec::new()), (UsbMode::Dfu, Some(_)) => reached_dfu(app, ctx, device, Again::Prepare), (_, Some(_)) => to_dfu(device, Again::Prepare, Some(mode)), } diff --git a/crates/flow/src/rules.rs b/crates/flow/src/rules.rs index ba60677..62ed02b 100644 --- a/crates/flow/src/rules.rs +++ b/crates/flow/src/rules.rs @@ -14,6 +14,9 @@ pub fn user_restarts(mode: UsbMode) -> bool { /// iOS and iPadOS 15.0: what the version question asks about. const FIFTEEN: Version = Version(15, 0, 0); +/// The answer "12 to 14" spans these: 12.0 up to the last 14. +const TWELVE: Version = Version(12, 0, 0); +const FOURTEEN: Version = Version(14, 0, 0); /// Whether a helper works on a device. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -71,10 +74,14 @@ impl Access { Fit::No } } - // "12 to 14": every route that reaches below 15. + // "12 to 14": a route that takes all of them; one that reaches + // below 15 but not over all of it (up to 13, say) may: + // it is checked once iOS runs. OsVersion::Below15 => { - if self.versions.iter().any(|(from, _)| *from < FIFTEEN) { + if self.versions.iter().any(|(from, to)| *from <= TWELVE && to.is_none_or(|to| to >= FOURTEEN)) { Fit::Yes + } else if self.versions.iter().any(|(from, _)| *from < FIFTEEN) { + Fit::Later } else { Fit::No } @@ -217,7 +224,7 @@ pub fn found(app: App, options: &Options, device: &Device, mode: UsbMode, restar mode => { let Some(helper) = helper(options, device) else { return waiting(Next::VersionUnsupported) }; let next = match (mode, helper) { - (UsbMode::Normal, Helper::Dopamine) => Next::RoomWithHelperApp, + (UsbMode::Normal, h) if h.is_app() => Next::RoomWithHelperApp, (UsbMode::Normal, _) => Next::RoomAfterRestart, (UsbMode::Recovery, _) => Next::RoomGuided, _ => Next::RoomFromDfu, @@ -254,7 +261,7 @@ pub struct OptionsView { pub fn options(kind: OptionsFor, options: &Options, device: &Device, pwned: bool, linux: bool) -> OptionsView { let taken_helper = helper(options, device); let taken_start = start(options, device, pwned); - let helpers = [Helper::Dopamine, Helper::Palera1n, Helper::Checkra1n] + let helpers = [Helper::Dopamine, Helper::Amethyst, Helper::Palera1n, Helper::Checkra1n] .into_iter() .map(|h| Choice { value: h, selected: taken_helper == Some(h), available: helper_fit(device, h) != Fit::No }) .collect(); diff --git a/crates/flow/src/tests.rs b/crates/flow/src/tests.rs index bdb8e8f..296a601 100644 --- a/crates/flow/src/tests.rs +++ b/crates/flow/src/tests.rs @@ -23,6 +23,7 @@ fn a10() -> Routes { Routes { access: vec![ Access { helper: Helper::Palera1n, versions: vec![(v("15.0"), None)] }, + Access { helper: Helper::Amethyst, versions: vec![(v("12.0"), Some(v("13.7")))] }, Access { helper: Helper::Checkra1n, versions: vec![(v("12.0"), Some(v("14.8.1")))] }, Access { helper: Helper::Dopamine, versions: vec![(v("15.0"), Some(v("18.7.1"))), (v("26.0"), Some(v("26.0.1")))] }, ], @@ -229,6 +230,27 @@ fn the_helper_follows_the_version() { assert_eq!(rules::helper(&checkra1n, &on(ipad6(), "17.7")), Some(Helper::Palera1n)); } +/// Amethyst where the data puts it: ahead of checkra1n within its versions, +/// checkra1n after them; the answer "12 to 14" may still be one of them. +#[test] +fn amethyst_takes_its_versions_in_the_datas_order() { + use rules::{default_helper, helper_fit, Fit}; + assert_eq!(default_helper(&on(ipad6(), "13.5")), Some(Helper::Amethyst)); + assert_eq!(default_helper(&on(ipad6(), "12.0")), Some(Helper::Amethyst)); + assert_eq!(default_helper(&on(ipad6(), "14.2")), Some(Helper::Checkra1n)); + assert_eq!(helper_fit(&on(ipad6(), "16.5"), Helper::Amethyst), Fit::No); + let below15 = Device { os: OsVersion::Below15, ..ipad6() }; + assert_eq!(helper_fit(&below15, Helper::Amethyst), Fit::Later); + assert_eq!(default_helper(&below15), Some(Helper::Checkra1n)); + // Where checkra1n doesn't reach (an A12), it is the one that may. + let a12 = Device { routes: Routes { access: vec![Access { helper: Helper::Amethyst, versions: vec![(v("12.0"), Some(v("13.7")))] }], boot: vec![Start::Ibss] }, ..below15 }; + assert_eq!(default_helper(&a12), Some(Helper::Amethyst)); + // Chosen where it can't work: the default. + let amethyst = Options { helper: Some(Helper::Amethyst), ..Options::default() }; + assert_eq!(rules::helper(&amethyst, &on(ipad6(), "14.2")), Some(Helper::Checkra1n)); + assert_eq!(rules::helper(&amethyst, &on(ipad6(), "13.5")), Some(Helper::Amethyst)); +} + #[test] fn from_pwned_dfu_only_ibss_starts() { use rules::{start, start_fits}; @@ -265,6 +287,13 @@ fn the_options_grey_what_cannot_work_and_keep_their_rows() { assert!(o.port_reset_enabled && o.busy_cpu_enabled); let checkra1n = options(OptionsFor::Helper, &defaults, &on(ipad6(), "14.8"), false, true); assert!(!checkra1n.palera1n_enabled && checkra1n.port_reset_enabled && checkra1n.busy_cpu_enabled); + // Amethyst: a choice of its own, taken within its versions, and like + // Dopamine no tool through DFU mode. + let o = options(OptionsFor::Helper, &defaults, &on(ipad6(), "13.5"), false, true); + let helper = |h| *o.helpers.iter().find(|c| c.value == h).unwrap(); + assert!(helper(Helper::Amethyst).selected && helper(Helper::Checkra1n).available && !helper(Helper::Dopamine).available); + assert!(!o.palera1n_enabled && !o.port_reset_enabled && !o.busy_cpu_enabled); + assert!(!options(OptionsFor::Helper, &defaults, &on(ipad6(), "16.5"), false, true).helpers.iter().any(|c| c.value == Helper::Amethyst && c.available)); } #[test] @@ -509,6 +538,36 @@ fn dopamine_signs_in_only_when_needed_then_waits_for_the_helper_app() { assert_eq!(kind(app, &s), ScreenKind::ChooseSplit); } +/// Amethyst is a helper app as Dopamine is: no DFU mode, signed and +/// installed while iOS runs, then the same steps and the split. +#[test] +fn amethyst_takes_the_helper_app_path() { + use rules::{found, Next}; + let app = App::Installer; + let ipad = on(ipad6(), "13.5"); + assert_eq!(found(app, &Options::default(), &ipad, UsbMode::Normal, false).next, Next::RoomWithHelperApp); + let (s, e) = run(app, State::start(), vec![seen(ipad.clone(), UsbMode::Normal), Event::Continue]); + assert_eq!(e, vec![Effect::InstallHelper(ipad.id.clone())]); + assert_eq!(kind(app, &s), ScreenKind::HelperInstalling); + let (s, _) = update(app, s, Event::HelperInstalled); + assert_eq!(kind(app, &s), ScreenKind::HelperSteps); + // The device restarts once on the way (Amethyst's first run): the steps stay. + let s = run(app, s, vec![Event::Detached { id: ipad.id.clone() }, seen(ipad.clone(), UsbMode::Normal)]).0; + assert_eq!(kind(app, &s), ScreenKind::HelperSteps); + let (s, _) = update(app, s, Event::IpadosReady { layout: fresh() }); + assert_eq!(kind(app, &s), ScreenKind::ChooseSplit); + // Out of recovery mode the installer restarts it for the app; out of DFU + // mode the user does. + let ctx = Ctx { options: Options { helper: Some(Helper::Amethyst), ..Options::default() }, at: Some(UsbMode::Normal) }; + let found = update(app, State::start(), recovery(Device { os: OsVersion::Exact(v("13.5")), ..ipad6() })).0; + let (s, e) = update_with(app, &ctx, found, Event::Continue); + assert_eq!(e, vec![Effect::PrepareRecovery(ipad6().id), Effect::RestartFromRecovery(ipad6().id)]); + assert_eq!(kind(app, &s), ScreenKind::Restarting); + let found = update(app, State::start(), dfu(Device { os: OsVersion::Exact(v("13.5")), ..ipad6() })).0; + let (s, e) = update_with(app, &ctx, found, Event::Continue); + assert!(e.is_empty() && matches!(s, State::Found { restart: true, .. })); +} + #[test] fn dopamine_needs_ios_running_the_installer_leaves_recovery_but_not_dfu() { let app = App::Installer; diff --git a/crates/runtime/src/access_dopamine.rs b/crates/runtime/src/access_dopamine.rs index d1b18c8..3267876 100644 --- a/crates/runtime/src/access_dopamine.rs +++ b/crates/runtime/src/access_dopamine.rs @@ -912,10 +912,9 @@ pub fn install_into(executor: &Executor, host: Host, access: &Access, signer: &S done } -/// The pinned Dopamine, into the cache ahead of its use. -pub fn fetch(executor: &Executor) -> Result<()> { - let receipt = Receipt { url: DOPAMINE.into(), bytes: DOPAMINE_BYTES, sha256: DOPAMINE_SHA256.into(), expanded_bytes: None }; - executor.download(&receipt).map(drop) +/// The pinned Dopamine or Amethyst, into the cache ahead of its use. +pub fn fetch(executor: &Executor, host: Host) -> Result<()> { + executor.download(&host.receipt()).map(drop) } /// Whether xtool holds an Apple sign-in from an earlier run. diff --git a/crates/runtime/src/demo.rs b/crates/runtime/src/demo.rs index 472c014..80617e2 100644 --- a/crates/runtime/src/demo.rs +++ b/crates/runtime/src/demo.rs @@ -20,6 +20,7 @@ fn ipad() -> Device { routes: Routes { access: vec![ Access { helper: Helper::Palera1n, versions: vec![(Version(15, 0, 0), None)] }, + Access { helper: Helper::Amethyst, versions: vec![(Version(12, 0, 0), Some(Version(13, 7, 0)))] }, Access { helper: Helper::Checkra1n, versions: vec![(Version(12, 0, 0), Some(Version(14, 8, 1)))] }, Access { helper: Helper::Dopamine, versions: vec![(Version(15, 0, 0), Some(Version(18, 7, 1))), (Version(26, 0, 0), Some(Version(26, 0, 1)))] }, ], diff --git a/crates/runtime/src/driver.rs b/crates/runtime/src/driver.rs index bb621fd..4ce258b 100644 --- a/crates/runtime/src/driver.rs +++ b/crates/runtime/src/driver.rs @@ -382,11 +382,15 @@ impl Driver { } }); } - // The helper app (Dopamine): signed and installed on a - // thread of its own; once it is there, the companion's + // The helper app (Dopamine, Amethyst): signed and installed + // on a thread of its own; once it is there, the companion's // connection is tried with its token. Effect::InstallHelper(ref id) | Effect::InstallHelperAgain(ref id) => { let again = matches!(effect, Effect::InstallHelperAgain(_)); + let host = match next.helper() { + Some(orchard_flow::Helper::Amethyst) => crate::access_dopamine::Host::Amethyst, + _ => crate::access_dopamine::Host::Dopamine, + }; let (udid, device) = (self.udids.get(id).cloned(), next.state.device().cloned()); let (executor, events, jobs) = (self.executor.clone(), self.events.clone(), self.companion_jobs.clone()); std::thread::spawn(move || { @@ -404,7 +408,7 @@ impl Driver { lines.push(step.to_owned()); let _ = events.send(Event::StartLog(lines.clone())); }; - let _ = events.send(match crate::helper_app::install(&executor, &udid, &say) { + let _ = events.send(match crate::helper_app::install(&executor, &udid, host, &say) { crate::helper_app::Outcome::Installed { token } => { let _ = jobs.send(CompanionJob::Attach { udid, device, token }); Event::HelperInstalled @@ -704,7 +708,7 @@ impl Driver { // helper app's on the route without DFU, else // the overlay's. let token = |udid: &str| match flow.helper() { - Some(orchard_flow::Helper::Dopamine) => crate::helper_app::token(&self.executor, udid), + Some(orchard_flow::Helper::Dopamine | orchard_flow::Helper::Amethyst) => crate::helper_app::token(&self.executor, udid), Some(orchard_flow::Helper::Checkra1n) => self.checkra1n.lock().expect("checkra1n").as_ref().map(|s| s.token.clone()), _ => self.executor.companion_token(), }; diff --git a/crates/runtime/src/exec.rs b/crates/runtime/src/exec.rs index d78f447..33c37fd 100644 --- a/crates/runtime/src/exec.rs +++ b/crates/runtime/src/exec.rs @@ -35,7 +35,7 @@ pub enum Tool { /// The iBSS route's way into the boot ROM. Gaster, /// The app the helper app is put into. - Dopamine, + Host(crate::access_dopamine::Host), } /// The tools of the helper and the start in effect in `flow`. @@ -52,7 +52,8 @@ pub fn tools_of(app: orchard_flow::App, flow: &orchard_flow::Flow) -> Vec match flow.helper() { Some(Helper::Palera1n) => add(Tool::Palera1n { two }), Some(Helper::Checkra1n) => add(Tool::Checkra1n), - Some(Helper::Dopamine) => add(Tool::Dopamine), + Some(Helper::Dopamine) => add(Tool::Host(crate::access_dopamine::Host::Dopamine)), + Some(Helper::Amethyst) => add(Tool::Host(crate::access_dopamine::Host::Amethyst)), None => {} } } @@ -259,7 +260,7 @@ impl Executor { let store = orchard_cache::store::Store::open(Some(&self.cache))?; orchard_usb::Host.gaster_worker(&store)?; } - Tool::Dopamine => crate::access_dopamine::fetch(self)?, + Tool::Host(host) => crate::access_dopamine::fetch(self, host)?, } } Ok(()) diff --git a/crates/runtime/src/helper_app.rs b/crates/runtime/src/helper_app.rs index 59ef53d..6cff865 100644 --- a/crates/runtime/src/helper_app.rs +++ b/crates/runtime/src/helper_app.rs @@ -1,10 +1,13 @@ //! The helper app on the route without DFU: the pinned Dopamine carrying //! the installer's companion (companion/out/access, built into the -//! installer), signed with the user's Apple ID and installed on the device. +//! installer), or on iOS 12 and 13 the pinned Amethyst carrying its build +//! for those versions (companion/out/access-ios12, with Amethyst's +//! executable built from its source), signed with the user's Apple ID and +//! installed on the device. //! Its helper takes the token the installer made for this device; the token //! and how long the signature lasts are kept, so a copy that is still good //! is not signed again. -use crate::access_dopamine::{self, Signer}; +use crate::access_dopamine::{self, Host, Signer}; use crate::exec::Executor; use crate::resize_app::Access; use orchard_cache::{Code, Error, Result}; @@ -46,32 +49,49 @@ pub fn forget(executor: &Executor, udid: &str) { let _ = std::fs::remove_file(record(executor, udid)); } -/// The companion's build for Dopamine, with the arguments its helper is +/// The companion's build for `host`, with the arguments its helper is /// started with. -fn access(token: &str) -> Result { - let missing = |what: &str| Error::new(Code::NotFound, format!("this installer was built without the helper app for Dopamine ({what})")); - let archive = crate::overlay::embedded(); +fn access(token: &str, host: Host) -> Result { + access_in(crate::overlay::embedded(), token, host) +} + +/// [`access`] from the companion's archive. +fn access_in(archive: &[u8], token: &str, host: Host) -> Result { + let (folder, name) = match host { + Host::Dopamine => ("access/", "Dopamine"), + Host::Amethyst => ("access-ios12/", "Amethyst"), + }; + let missing = |what: &str| Error::new(Code::NotFound, format!("this installer was built without the helper app for {name} ({what})")); if archive.is_empty() { return Err(missing("no companion")); } let archive = orchard_formats::tar::read(archive)?; let mut info = None; let mut library = None; + let mut executable = None; let mut resources = Vec::new(); for file in &archive.files { - let Some(path) = file.path.strip_prefix("access/") else { continue }; + let Some(path) = file.path.strip_prefix(folder) else { continue }; if path == "Info.plist" { info = Some(file.data.to_vec()); } else if let Some(resource) = path.strip_prefix("Resources/") { resources.push((resource.to_owned(), file.data.to_vec())); + } else if path == "host/Amethyst" { + executable = Some(file.data.to_vec()); } else if path.ends_with(".dylib") && !path.contains('/') { library = Some(file.data.to_vec()); } } + // Amethyst's own executable is stripped: the one built from its source + // takes its place. + let host = match host { + Host::Amethyst => Some(executable.ok_or_else(|| missing("no Amethyst executable"))?), + Host::Dopamine => None, + }; // Split on spaces on the device: a space in the name goes as %20. let system = orchard_flow::system_name().replace(' ', "%20"); resources.push(("helper-arguments.txt".to_owned(), format!("--token {token}\n--system {system}\n").into_bytes())); - Ok(Access { info: info.ok_or_else(|| missing("no Info.plist"))?, library: library.ok_or_else(|| missing("no library"))?, resources, host: None }) + Ok(Access { info: info.ok_or_else(|| missing("no Info.plist"))?, library: library.ok_or_else(|| missing("no library"))?, resources, host }) } /// What installing the helper app came to. @@ -83,27 +103,43 @@ pub enum Outcome { Failed(String), } -/// Signs the helper app and installs it on the device `udid`: with the -/// account Xcode is signed in to where that is one, else with xtool. -/// `say` is told each step, for the window's Details. -pub fn install(executor: &Executor, udid: &str, say: &dyn Fn(&str)) -> Outcome { +/// Who signs the helper app: for Dopamine the account Xcode is signed in to +/// where that is one, else xtool; for Amethyst always xtool, since Xcode +/// builds nothing for iOS 12 and 13. None: xtool has no build here. +fn signer(host: Host, xcode_teams: impl FnOnce() -> Vec, xtool_here: bool) -> std::result::Result, String> { + if host == Host::Dopamine { + if let [team] = xcode_teams().as_slice() { + return Ok(Some(Signer::Xcode { team: team.clone() })); + } + } + match (xtool_here, host) { + (true, _) => Ok(None), + (false, Host::Dopamine) => Err("nothing on this computer signs apps with an Apple ID".into()), + (false, Host::Amethyst) => Err("the helper app for iOS 12 and 13 is signed with xtool (Xcode builds nothing for those versions), and xtool publishes no build for this computer".into()), + } +} + +/// Signs the helper app (put into `host`) and installs it on the device +/// `udid`. `say` is told each step, for the window's Details. +pub fn install(executor: &Executor, udid: &str, host: Host, say: &dyn Fn(&str)) -> Outcome { if let Some(token) = token(executor, udid) { return Outcome::Installed { token }; } let work = executor.cache().join("work"); let _ = std::fs::create_dir_all(&work); - let signer = match access_dopamine::teams(&work) { - Ok(teams) if teams.len() == 1 => Signer::Xcode { team: teams[0].0.clone() }, - _ if access_dopamine::xtool_here() => match access_dopamine::signed_in(executor) { + let teams = || access_dopamine::teams(&work).map(|t| t.into_iter().map(|(team, _)| team).collect()).unwrap_or_default(); + let signer = match signer(host, teams, access_dopamine::xtool_here()) { + Ok(Some(signer)) => signer, + Ok(None) => match access_dopamine::signed_in(executor) { Ok(true) => Signer::Xtool, Ok(false) => return Outcome::NeedsSignIn, Err(e) => return Outcome::Failed(e.to_string()), }, - _ => return Outcome::Failed("nothing on this computer signs apps with an Apple ID".into()), + Err(why) => return Outcome::Failed(why), }; let token = crate::overlay::Identity::random().token_hex(); - let installed = access(&token).and_then(|access| { - access_dopamine::install(executor, &access, &signer, udid, IDENTIFIER, &|step| { + let installed = access(&token, host).and_then(|access| { + access_dopamine::install_into(executor, host, &access, &signer, udid, IDENTIFIER, &|step| { eprintln!("{} helper app: {step}", crate::install::stamp()); say(step); }) @@ -120,3 +156,56 @@ pub fn install(executor: &Executor, udid: &str, say: &dyn Fn(&str)) -> Outcome { } Outcome::Installed { token } } + +#[cfg(test)] +mod tests { + use super::*; + + fn archive(files: &[(&str, &[u8])]) -> Vec { + let entries: Vec = files.iter().map(|(path, data)| orchard_formats::tar::Entry { path, mode: 0o644, data }).collect(); + orchard_formats::tar::write(&entries).unwrap() + } + + /// Each host takes its own build of the companion; Amethyst's needs its + /// executable built from source, Dopamine's has none. + #[test] + fn each_host_takes_its_own_build() { + let both = archive(&[ + ("orchard-companion", b"helper"), + ("access/Info.plist", b"info-15"), + ("access/OrchardCompanion.dylib", b"library-15"), + ("access/Resources/orchard-companion.payload", b"payload-15"), + ("access-ios12/Info.plist", b"info-12"), + ("access-ios12/OrchardCompanion.dylib", b"library-12"), + ("access-ios12/Resources/orchard-companion.payload", b"payload-12"), + ("access-ios12/host/Amethyst", b"amethyst"), + ]); + let dopamine = access_in(&both, "ab", Host::Dopamine).unwrap(); + assert_eq!((dopamine.info.as_slice(), dopamine.library.as_slice(), dopamine.host), (&b"info-15"[..], &b"library-15"[..], None)); + assert!(dopamine.resources.iter().any(|(p, d)| p == "orchard-companion.payload" && d == b"payload-15")); + let amethyst = access_in(&both, "ab", Host::Amethyst).unwrap(); + assert_eq!((amethyst.info.as_slice(), amethyst.library.as_slice()), (&b"info-12"[..], &b"library-12"[..])); + assert_eq!(amethyst.host.as_deref(), Some(&b"amethyst"[..])); + assert!(amethyst.resources.iter().any(|(p, d)| p == "orchard-companion.payload" && d == b"payload-12")); + assert!(amethyst.resources.iter().any(|(p, d)| p == "helper-arguments.txt" && String::from_utf8_lossy(d).starts_with("--token ab\n"))); + // An installer built before Amethyst's part says so. + let older = archive(&[("orchard-companion", b"helper"), ("access/Info.plist", b"i"), ("access/OrchardCompanion.dylib", b"l")]); + let missing = access_in(&older, "ab", Host::Amethyst).err().unwrap().to_string(); + assert!(missing.contains("without the helper app for Amethyst"), "{missing}"); + let no_host = archive(&[("access-ios12/Info.plist", b"i"), ("access-ios12/OrchardCompanion.dylib", b"l")]); + assert!(access_in(&no_host, "ab", Host::Amethyst).err().unwrap().to_string().contains("no Amethyst executable")); + } + + /// Amethyst is signed by xtool only: never by Xcode's account, and where + /// xtool has no build the reason says so. + #[test] + fn amethyst_signs_with_xtool_only() { + let one = || vec!["TEAM1".to_owned()]; + assert!(matches!(signer(Host::Dopamine, one, true), Ok(Some(Signer::Xcode { .. })))); + assert!(matches!(signer(Host::Dopamine, Vec::new, true), Ok(None))); + assert!(signer(Host::Dopamine, Vec::new, false).is_err()); + assert!(matches!(signer(Host::Amethyst, one, true), Ok(None))); + let why = signer(Host::Amethyst, one, false).err().unwrap(); + assert!(why.contains("xtool") && why.contains("Xcode builds nothing"), "{why}"); + } +} diff --git a/crates/runtime/src/lib.rs b/crates/runtime/src/lib.rs index bf9f288..17ab7e7 100644 --- a/crates/runtime/src/lib.rs +++ b/crates/runtime/src/lib.rs @@ -96,6 +96,7 @@ fn routes_of(catalog: &Catalog, board: &Board) -> Routes { "palera1n" => Helper::Palera1n, "checkra1n" => Helper::Checkra1n, "dopamine" => Helper::Dopamine, + "amethyst" => Helper::Amethyst, _ => return None, }; let fits = on_chip(offer.route); diff --git a/docs/install.md b/docs/install.md index c09ec55..efa9647 100644 --- a/docs/install.md +++ b/docs/install.md @@ -91,7 +91,7 @@ Nothing is asked. What no option answers ends the run with exit status 5 and names the option: `--yes`, `--password-file`, `--pin-file`, `--split GB`, `--replace` or `--another` (with `--disk`), `--apple-id` with `--apple-password-file`. Apple's sign-in code can only be -typed, so a first sign-in with the Dopamine helper needs a terminal. +typed, so a first sign-in with the Dopamine or Amethyst helper needs a terminal. Resizing and SSH are off unless their options are given, and a system snapshot stays unless `--remove-snapshot` or `--yes` is given. @@ -152,8 +152,9 @@ first route that fits the device and its version is taken. | `palera1n` | the device goes through DFU mode, and palera1n starts iPadOS with the helper (iPadOS 15 and later) | | `checkra1n` | the same with checkra1n (iOS 12 to 14) | | `dopamine` | a helper app is signed with your Apple ID and installed while iPadOS runs; no DFU mode for this step | +| `amethyst` | the same in the Amethyst app, for iOS 12.0 to 13.7 (where the data puts it); the device restarts once on the way | -With `dopamine` the run asks for the Apple ID and its password +With `dopamine` and `amethyst` the run asks for the Apple ID and its password (`--apple-id ID`, `--apple-password-file FILE`), then for the code Apple sends to your devices, where Apple asks for one. They go only to Apple. A sign-in that Xcode or an earlier run left on this computer is used without @@ -161,6 +162,13 @@ asking. The run then lists the steps on the device (Developer Mode, trusting the Apple ID, opening the app) and goes on when the app answers; `r` installs the app again. +`amethyst` always signs with xtool: Xcode builds nothing for iOS 12 and 13, +so an Xcode sign-in is not used, and a computer xtool has no build for +can't take this route (the run says so). iOS 12 and 13 have no Developer +Mode: the steps are trusting the Apple ID and opening the app. The first +time, the device restarts once: open Orchard Installer again when it is back +and tap Continue again. + ## DFU mode - **In a terminal**: orchard restarts the device into recovery mode, and a diff --git a/ios-installer/build.sh b/ios-installer/build.sh index f3b4e4a..effbf5b 100755 --- a/ios-installer/build.sh +++ b/ios-installer/build.sh @@ -12,7 +12,7 @@ # crates/inapp. set -euo pipefail cd "$(dirname "$0")" -RESIZE_APFS_COMMIT=cd1f9db334af55104884aca77edfcd2a327140e2 +RESIZE_APFS_COMMIT=ade540a2dd457173d85e11e73cfe4293cc5b4696 root=$PWD resize=${RESIZE_APFS:-$root/../../resize-apfs-engine} actual=$(git -C "$resize" rev-parse HEAD)