Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add vphone-launchpad, a workstation app for bundles and VMs

Lakr2333c601f6042f4
diff --git a/.gitignore b/.gitignore
index a5bc447e..5420651b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -351,3 +351,7 @@ setup_logs/
/vm.backups
/vm-*/
/debs/
+
+# vphone-launchpad signing team; never committed
+VPhoneLaunchpad/Configuration/Developer.xcconfig
+VPhoneLaunchpad/Configuration/DevelopmentDeveloper.xcconfig
diff --git a/AGENTS.md b/AGENTS.md
index 8f82fec9..8b85affe 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -48,13 +48,15 @@ See `Research/` for detailed firmware pipeline, component origins, patch breakdo
- `VPhoneKit`: shared core, archive, and external access kits with their tests.
- `VPhoneDaemon`: guest `vphoned`, native operations, and daemon configuration.
- `VPhoneGuestComponents`: guest dylibs built by Makefile from the bundle build phase.
+- `VPhoneLaunchpad`: `vphone-launchpad.app`, the workstation app that downloads and manages `VPhone.bundle` releases and drives VMs through the active bundle's `vphone-cli`, plus its SMJobBless helper `com.vphone.launchpad.helper`. Shipped separately from the bundle. Settings live only in `VPhoneLaunchpad/Configuration/*.xcconfig`; the pbxproj holds none.
The `VPhone` scheme puts all shipped Mach-O files in `VPhone.bundle/Contents/MacOS`. Guest configuration is in `Contents/Resources`. Xcode targets have `CODE_SIGNING_ALLOWED=NO`; the bundle build phase signs each binary ad hoc with only its own entitlements, then seals the outer bundle. `VPhoneVirtualization.entitlements` belongs to `vphone-vm`; `VPhoneDaemon.entitlements` belongs to `vphoned`. The bundle and CLI have no private entitlements.
### Key Patterns
- `vphone-cli` is the unentitled entry point. `VPhoneGuestLaunchPlanner` resolves `vphone-vm` beside the running executable, checks its entitlements, probes AMFI, and reports the exact allowlist command on refusal. It never obtains root itself.
-- `VPhoneEscalator` manages AMFI cdhash admission only. It writes amfid heap state, not executable code. Root authorization and installation are owned by the user or a future workstation application; this repository has no SMJobBless or sudo password flow.
+- `VPhoneEscalator` manages AMFI cdhash admission only. It writes amfid heap state, not executable code. Root authorization belongs to the user or to `vphone-launchpad`; neither `vphone-cli` nor the bundle has an SMJobBless or sudo password flow.
+- `vphone-launchpad` has no entitlements. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles` and runs `cfw install` from that store after rechecking the recorded cdhash. There is no generic command verb. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.
- Host VM artifacts, caches, and archives created by vphone use mode `0777` for workstation access. Symlinks are not followed when changing permissions. Guest filesystem modes inside `Disk.img` remain unchanged.
- `VPhoneRestore` runs in the CLI process over vendored libirecovery and idevicerestore. No Python or runtime Homebrew dependency is allowed.
- The VM process owns AppKit windows and the guest control connection. `vphoned` serves HTTP and WebSocket over VSOCK 1339, with camera data on 1338.
@@ -131,3 +133,5 @@ The VM process requires private entitlements for PV=3 virtualization. Build the
- **Typography:** System monospace (SF Mono / Menlo) for UI and log output.
- **Depth:** Flat with 1px borders (`#333333`). No shadows.
- **Spacing:** 8px base unit, 12px component padding, 16px section gaps.
+
+`vphone-launchpad` is the exception: it is a native SwiftUI Mac app. It uses system controls, grouped `Form`s, `Table`, SF Symbols, toolbar buttons for page actions, and the system appearance. Monospace is only for command text and logs.
diff --git a/VPhone.xcworkspace/contents.xcworkspacedata b/VPhone.xcworkspace/contents.xcworkspacedata
index bdcc87b8..207d983f 100644
--- a/VPhone.xcworkspace/contents.xcworkspacedata
+++ b/VPhone.xcworkspace/contents.xcworkspacedata
@@ -19,4 +19,7 @@
<FileRef
location = "group:VPhoneExecutable/VPhoneEscalator/VPhoneEscalator.xcodeproj">
</FileRef>
+ <FileRef
+ location = "group:VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj">
+ </FileRef>
</Workspace>
diff --git a/VPhoneLaunchpad/Build/SignLaunchpad.sh b/VPhoneLaunchpad/Build/SignLaunchpad.sh
new file mode 100644
index 00000000..567cdd81
--- /dev/null
+++ b/VPhoneLaunchpad/Build/SignLaunchpad.sh
@@ -0,0 +1,30 @@
+#!/bin/zsh
+# Sign a built vphone-launchpad.app for distribution. The Xcode build never
+# signs; run this afterwards with a Developer ID Application identity from the
+# team the app was built for (VPHONE_LAUNCHPAD_TEAM in the gitignored
+# Configuration/Developer.xcconfig).
+#
+# zsh VPhoneLaunchpad/Build/SignLaunchpad.sh <path/to/vphone-launchpad.app> "Developer ID Application: …"
+#
+# The helper is signed before the app that seals it. Neither gets
+# entitlements. Afterwards the helper is checked against the app's
+# SMPrivilegedExecutables requirement, which is what SMJobBless enforces.
+set -euo pipefail
+
+app=${1:?usage: SignLaunchpad.sh <vphone-launchpad.app> <identity>}
+identity=${2:?usage: SignLaunchpad.sh <vphone-launchpad.app> <identity>}
+label=com.vphone.launchpad.helper
+helper="$app/Contents/Library/LaunchServices/$label"
+
+requirement=$(/usr/libexec/PlistBuddy -c "Print :SMPrivilegedExecutables:$label" "$app/Contents/Info.plist")
+if [[ $requirement == *'subject.OU] = ""'* ]]; then
+ print -u2 "error: $app was built without VPHONE_LAUNCHPAD_TEAM; set it in Configuration/Developer.xcconfig and rebuild."
+ exit 1
+fi
+
+codesign --force --options runtime --timestamp --sign "$identity" "$helper"
+codesign --force --options runtime --timestamp --sign "$identity" "$app"
+
+codesign --verify --strict --deep "$app"
+codesign --verify --strict -R="$requirement" "$helper"
+print "signed $app"
diff --git a/VPhoneLaunchpad/Configuration/Base.xcconfig b/VPhoneLaunchpad/Configuration/Base.xcconfig
new file mode 100644
index 00000000..39f7aa76
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/Base.xcconfig
@@ -0,0 +1,41 @@
+#include "Version.xcconfig"
+
+// Everything in this file is a deliberate choice. Anything Xcode already
+// defaults to correctly is left out on purpose — do not re-add settings just
+// because the template used to emit them. Target xcconfigs hold only what
+// differs between the app and the helper; the pbxproj holds no settings.
+
+// Nothing is signed at build time, like every other target in the workspace.
+// Signing is a separate step with a Developer ID identity, run by whoever
+// distributes the app: Build/SignLaunchpad.sh. Leaving CODE_SIGNING_ALLOWED
+// on would sign with whatever identity the build machine happens to have.
+CODE_SIGNING_ALLOWED = NO
+
+// The team pinned by SMPrivilegedExecutables (app → helper) and
+// SMAuthorizedClients (helper → app). It is never committed: set it in a
+// local, gitignored Configuration/Developer.xcconfig. Left empty, the app
+// builds and runs, and Host Setup reports that the helper cannot be installed.
+VPHONE_LAUNCHPAD_TEAM =
+
+// vphone runs only on Apple silicon (PV=3 guests), so an Intel slice would be
+// a binary that can never do its job.
+ARCHS = arm64
+SDKROOT = macosx
+// vphone-cli's own floor: Sequoia.
+MACOSX_DEPLOYMENT_TARGET = 15.0
+
+// Xcode warns that traditional headermaps are no longer supported. There is
+// no C in these targets to search user paths for.
+ALWAYS_SEARCH_USER_PATHS = NO
+
+// Swift 6 language mode with approachable concurrency: the app module is
+// @MainActor by default and `nonisolated` async functions stay on the
+// caller's actor. Anything that must run off the main actor says so
+// explicitly — the process reader threads, downloads, and all shared code.
+// The helper target overrides the default isolation to nonisolated.
+SWIFT_VERSION = 6.0
+SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor
+SWIFT_APPROACHABLE_CONCURRENCY = YES
+
+// Local developer overrides (optional, gitignored).
+#include? "Developer.xcconfig"
diff --git a/VPhoneLaunchpad/Configuration/Development.xcconfig b/VPhoneLaunchpad/Configuration/Development.xcconfig
new file mode 100644
index 00000000..4f00276f
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/Development.xcconfig
@@ -0,0 +1,12 @@
+#include "Base.xcconfig"
+
+SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) DEBUG
+
+// Like PRODUCT_NAME, these are Xcode-template settings, not build-system
+// defaults — the default optimization is -O in every configuration, and
+// previews hard-require -Onone ("Not built with -Onone").
+SWIFT_OPTIMIZATION_LEVEL = -Onone
+ONLY_ACTIVE_ARCH = YES
+DEBUG_INFORMATION_FORMAT = dwarf
+
+#include? "DevelopmentDeveloper.xcconfig"
diff --git a/VPhoneLaunchpad/Configuration/Release.xcconfig b/VPhoneLaunchpad/Configuration/Release.xcconfig
new file mode 100644
index 00000000..d8e8e33e
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/Release.xcconfig
@@ -0,0 +1,4 @@
+#include "Base.xcconfig"
+
+// Nothing to add: Xcode's Release defaults (-O, wholemodule) are already what
+// we want.
diff --git a/VPhoneLaunchpad/Configuration/VPhoneLaunchpad.xcconfig b/VPhoneLaunchpad/Configuration/VPhoneLaunchpad.xcconfig
new file mode 100644
index 00000000..2322a27e
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/VPhoneLaunchpad.xcconfig
@@ -0,0 +1,12 @@
+// The app. Build configuration (Development or Release) comes from the
+// project level; this file only names the product.
+
+PRODUCT_NAME = vphone-launchpad
+// PRODUCT_NAME has a dash, which is not a valid Swift module name.
+PRODUCT_MODULE_NAME = VPhoneLaunchpad
+PRODUCT_BUNDLE_IDENTIFIER = com.vphone.launchpad
+// Hand-written so SMPrivilegedExecutables can carry the helper requirement.
+// Outside the synchronized group: a build input, not a bundled resource.
+GENERATE_INFOPLIST_FILE = NO
+INFOPLIST_FILE = Resources/VPhoneLaunchpad.Info.plist
+LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks
diff --git a/VPhoneLaunchpad/Configuration/VPhoneLaunchpadHelper.xcconfig b/VPhoneLaunchpad/Configuration/VPhoneLaunchpadHelper.xcconfig
new file mode 100644
index 00000000..5caaefc6
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/VPhoneLaunchpadHelper.xcconfig
@@ -0,0 +1,16 @@
+// The SMJobBless helper. SMJobBless requires the file name to equal the
+// launchd label and both plists to be embedded in the Mach-O.
+
+PRODUCT_NAME = com.vphone.launchpad.helper
+PRODUCT_MODULE_NAME = VPhoneLaunchpadHelper
+PRODUCT_BUNDLE_IDENTIFIER = com.vphone.launchpad.helper
+GENERATE_INFOPLIST_FILE = NO
+INFOPLIST_FILE = Resources/VPhoneLaunchpadHelper.Info.plist
+CREATE_INFOPLIST_SECTION_IN_BINARY = YES
+OTHER_LDFLAGS = $(inherited) -sectcreate __TEXT __launchd_plist $(SRCROOT)/Resources/VPhoneLaunchpadHelper.Launchd.plist
+// Embedded in the app, never installed on its own.
+SKIP_INSTALL = YES
+
+// A daemon has no main actor worth defaulting to: XPC replies and child
+// processes all run on background queues.
+SWIFT_DEFAULT_ACTOR_ISOLATION = nonisolated
diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfig
new file mode 100644
index 00000000..170dae5e
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig
@@ -0,0 +1,4 @@
+MARKETING_VERSION = 0.1.0
+// Bump whenever the helper changes. The app blesses the helper again when the
+// running helper's CFBundleVersion differs from the copy it embeds.
+CURRENT_PROJECT_VERSION = 1
diff --git a/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist b/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist
new file mode 100644
index 00000000..626487e1
--- /dev/null
+++ b/VPhoneLaunchpad/Resources/VPhoneLaunchpad.Info.plist
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>vphone-launchpad</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>vphone-launchpad</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>LSApplicationCategoryType</key>
+ <string>public.app-category.developer-tools</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>$(MACOSX_DEPLOYMENT_TARGET)</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+ <key>SMPrivilegedExecutables</key>
+ <dict>
+ <key>com.vphone.launchpad.helper</key>
+ <string>anchor apple generic and identifier "com.vphone.launchpad.helper" and certificate leaf[subject.OU] = "$(VPHONE_LAUNCHPAD_TEAM)"</string>
+ </dict>
+</dict>
+</plist>
diff --git a/VPhoneLaunchpad/Resources/VPhoneLaunchpadHelper.Info.plist b/VPhoneLaunchpad/Resources/VPhoneLaunchpadHelper.Info.plist
new file mode 100644
index 00000000..18cfac90
--- /dev/null
+++ b/VPhoneLaunchpad/Resources/VPhoneLaunchpadHelper.Info.plist
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>SMAuthorizedClients</key>
+ <array>
+ <string>anchor apple generic and identifier "com.vphone.launchpad" and certificate leaf[subject.OU] = "$(VPHONE_LAUNCHPAD_TEAM)"</string>
+ </array>
+</dict>
+</plist>
diff --git a/VPhoneLaunchpad/Resources/VPhoneLaunchpadHelper.Launchd.plist b/VPhoneLaunchpad/Resources/VPhoneLaunchpadHelper.Launchd.plist
new file mode 100644
index 00000000..ba5eb2ee
--- /dev/null
+++ b/VPhoneLaunchpad/Resources/VPhoneLaunchpadHelper.Launchd.plist
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.vphone.launchpad.helper</string>
+ <key>MachServices</key>
+ <dict>
+ <key>com.vphone.launchpad.helper</key>
+ <true/>
+ </dict>
+</dict>
+</plist>
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
new file mode 100644
index 00000000..72d367b3
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
@@ -0,0 +1,110 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {};
+ objectVersion = 70;
+ objects = {
+/* Begin PBXBuildFile section */
+ 5A1000000000000000000061 /* com.vphone.launchpad.helper in Embed Privileged Helper */ = {isa = PBXBuildFile; fileRef = 5A1000000000000000000032 /* com.vphone.launchpad.helper */; };
+/* End PBXBuildFile section */
+/* Begin PBXContainerItemProxy section */
+ 5A1000000000000000000071 /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A1000000000000000000012; remoteInfo = VPhoneLaunchpadHelper; };
+/* End PBXContainerItemProxy section */
+/* Begin PBXCopyFilesBuildPhase section */
+ 5A1000000000000000000053 /* Embed Privileged Helper */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = Contents/Library/LaunchServices; dstSubfolderSpec = 1; files = (5A1000000000000000000061 /* com.vphone.launchpad.helper in Embed Privileged Helper */, ); name = "Embed Privileged Helper"; runOnlyForDeploymentPostprocessing = 0; };
+/* End PBXCopyFilesBuildPhase section */
+/* Begin PBXFileReference section */
+ 5A1000000000000000000031 /* vphone-launchpad.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "vphone-launchpad.app"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 5A1000000000000000000032 /* com.vphone.launchpad.helper */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = com.vphone.launchpad.helper; sourceTree = BUILT_PRODUCTS_DIR; };
+ 5A1000000000000000000033 /* Base.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Base.xcconfig; sourceTree = "<group>"; };
+ 5A1000000000000000000034 /* VPhoneLaunchpad.Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = VPhoneLaunchpad.Info.plist; sourceTree = "<group>"; };
+ 5A1000000000000000000035 /* VPhoneLaunchpadHelper.Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = VPhoneLaunchpadHelper.Info.plist; sourceTree = "<group>"; };
+ 5A1000000000000000000036 /* VPhoneLaunchpadHelper.Launchd.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = VPhoneLaunchpadHelper.Launchd.plist; sourceTree = "<group>"; };
+ 5A1000000000000000000037 /* Version.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Version.xcconfig; sourceTree = "<group>"; };
+ 5A1000000000000000000038 /* Development.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Development.xcconfig; sourceTree = "<group>"; };
+ 5A1000000000000000000039 /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
+ 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpad.xcconfig; sourceTree = "<group>"; };
+ 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpadHelper.xcconfig; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+/* Begin PBXFileSystemSynchronizedRootGroup section */
+ 5A1000000000000000000021 /* VPhoneLaunchpad */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpad; sourceTree = "<group>"; };
+ 5A1000000000000000000022 /* VPhoneLaunchpadHelper */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadHelper; sourceTree = "<group>"; };
+ 5A1000000000000000000023 /* VPhoneLaunchpadShared */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadShared; sourceTree = "<group>"; };
+/* End PBXFileSystemSynchronizedRootGroup section */
+/* Begin PBXFrameworksBuildPhase section */
+ 5A1000000000000000000041 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+ 5A1000000000000000000042 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+/* End PBXFrameworksBuildPhase section */
+/* Begin PBXGroup section */
+ 5A1000000000000000000002 = {isa = PBXGroup; children = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000022 /* VPhoneLaunchpadHelper */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, 5A1000000000000000000004 /* Configuration */, 5A1000000000000000000005 /* Resources */, 5A1000000000000000000003 /* Products */, ); sourceTree = "<group>"; };
+ 5A1000000000000000000003 /* Products */ = {isa = PBXGroup; children = (5A1000000000000000000031 /* vphone-launchpad.app */, 5A1000000000000000000032 /* com.vphone.launchpad.helper */, ); name = Products; sourceTree = "<group>"; };
+ 5A1000000000000000000004 /* Configuration */ = {isa = PBXGroup; children = (5A1000000000000000000037 /* Version.xcconfig */, 5A1000000000000000000033 /* Base.xcconfig */, 5A1000000000000000000038 /* Development.xcconfig */, 5A1000000000000000000039 /* Release.xcconfig */, 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */, 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */, ); path = Configuration; sourceTree = "<group>"; };
+ 5A1000000000000000000005 /* Resources */ = {isa = PBXGroup; children = (5A1000000000000000000034 /* VPhoneLaunchpad.Info.plist */, 5A1000000000000000000035 /* VPhoneLaunchpadHelper.Info.plist */, 5A1000000000000000000036 /* VPhoneLaunchpadHelper.Launchd.plist */, ); path = Resources; sourceTree = "<group>"; };
+/* End PBXGroup section */
+/* Begin PBXNativeTarget section */
+ 5A1000000000000000000011 /* VPhoneLaunchpad */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */;
+ buildPhases = (5A1000000000000000000051 /* Sources */, 5A1000000000000000000041 /* Frameworks */, 5A1000000000000000000052 /* Resources */, 5A1000000000000000000053 /* Embed Privileged Helper */, );
+ buildRules = ();
+ dependencies = (5A1000000000000000000072 /* PBXTargetDependency */, );
+ fileSystemSynchronizedGroups = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );
+ name = VPhoneLaunchpad;
+ productName = VPhoneLaunchpad;
+ productReference = 5A1000000000000000000031 /* vphone-launchpad.app */;
+ productType = "com.apple.product-type.application";
+ };
+ 5A1000000000000000000012 /* VPhoneLaunchpadHelper */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 5A1000000000000000000093 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadHelper" */;
+ buildPhases = (5A1000000000000000000054 /* Sources */, 5A1000000000000000000042 /* Frameworks */, );
+ buildRules = ();
+ dependencies = ();
+ fileSystemSynchronizedGroups = (5A1000000000000000000022 /* VPhoneLaunchpadHelper */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );
+ name = VPhoneLaunchpadHelper;
+ productName = VPhoneLaunchpadHelper;
+ productReference = 5A1000000000000000000032 /* com.vphone.launchpad.helper */;
+ productType = "com.apple.product-type.tool";
+ };
+/* End PBXNativeTarget section */
+/* Begin PBXProject section */
+ 5A1000000000000000000001 /* Project object */ = {
+ isa = PBXProject;
+ attributes = {LastUpgradeCheck = 2700; };
+ buildConfigurationList = 5A1000000000000000000091 /* Build configuration list for PBXProject "VPhoneLaunchpad" */;
+ compatibilityVersion = "Xcode 16.0";
+ developmentRegion = en;
+ knownRegions = (en, Base, );
+ mainGroup = 5A1000000000000000000002;
+ productRefGroup = 5A1000000000000000000003 /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (5A1000000000000000000011 /* VPhoneLaunchpad */, 5A1000000000000000000012 /* VPhoneLaunchpadHelper */, );
+ };
+/* End PBXProject section */
+/* Begin PBXResourcesBuildPhase section */
+ 5A1000000000000000000052 /* Resources */ = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+/* End PBXResourcesBuildPhase section */
+/* Begin PBXSourcesBuildPhase section */
+ 5A1000000000000000000051 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+ 5A1000000000000000000054 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+/* End PBXSourcesBuildPhase section */
+/* Begin PBXTargetDependency section */
+ 5A1000000000000000000072 /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 5A1000000000000000000012 /* VPhoneLaunchpadHelper */; targetProxy = 5A1000000000000000000071 /* PBXContainerItemProxy */; };
+/* End PBXTargetDependency section */
+/* Begin XCBuildConfiguration section */
+ 5A1000000000000000000081 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A1000000000000000000038 /* Development.xcconfig */; buildSettings = {}; name = Debug; };
+ 5A1000000000000000000082 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A1000000000000000000039 /* Release.xcconfig */; buildSettings = {}; name = Release; };
+ 5A1000000000000000000083 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */; buildSettings = {}; name = Debug; };
+ 5A1000000000000000000084 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */; buildSettings = {}; name = Release; };
+ 5A1000000000000000000085 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */; buildSettings = {}; name = Debug; };
+ 5A1000000000000000000086 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */; buildSettings = {}; name = Release; };
+/* End XCBuildConfiguration section */
+/* Begin XCConfigurationList section */
+ 5A1000000000000000000091 /* Build configuration list for PBXProject "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000081 /* Debug */, 5A1000000000000000000082 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
+ 5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000083 /* Debug */, 5A1000000000000000000084 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
+ 5A1000000000000000000093 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadHelper" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000085 /* Debug */, 5A1000000000000000000086 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
+/* End XCConfigurationList section */
+ };
+ rootObject = 5A1000000000000000000001 /* Project object */;
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
new file mode 100644
index 00000000..62df770e
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadApp.swift
@@ -0,0 +1,45 @@
+import AppKit
+import SwiftUI
+
+@main
+struct VPhoneLaunchpadApp: App {
+ @NSApplicationDelegateAdaptor(VPhoneLaunchpadAppDelegate.self) private var delegate
+ @State private var model = VPhoneLaunchpadModel()
+
+ var body: some Scene {
+ Window("vphone-launchpad", id: "main") {
+ VPhoneLaunchpadRootView()
+ .environment(model)
+ .frame(minWidth: 820, minHeight: 560)
+ .onAppear { delegate.model = model }
+ }
+ .windowToolbarStyle(.unified(showsTitle: false))
+ .commands {
+ CommandGroup(replacing: .newItem) {}
+ }
+ }
+}
+
+/// Guests keep running when Launchpad quits (their output goes to a log
+/// file, not a pipe). A machine being created does not survive, so quitting
+/// then asks first.
+@MainActor
+final class VPhoneLaunchpadAppDelegate: NSObject, NSApplicationDelegate {
+ weak var model: VPhoneLaunchpadModel?
+
+ func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool {
+ true
+ }
+
+ func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {
+ guard let model, model.machines.hasActiveCreation else {
+ return .terminateNow
+ }
+ let alert = NSAlert()
+ alert.messageText = "Stop creating the machine?"
+ alert.informativeText = "Quitting stops the New Machine pipeline. You can retry it later from the step it stopped at."
+ alert.addButton(withTitle: "Quit")
+ alert.addButton(withTitle: "Cancel")
+ return alert.runModal() == .alertFirstButtonReturn ? .terminateNow : .terminateCancel
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
new file mode 100644
index 00000000..bc5eb157
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
@@ -0,0 +1,152 @@
+import Foundation
+import Observation
+
+/// Owns the three stages and decides which of them the segmented control
+/// shows. Host Setup is always there; Core Bundle appears once the required
+/// host checks pass; Machines appears once the active bundle passes host
+/// preflight. After setup has completed once, all three stay visible and a
+/// regression only marks Host Setup, so machines are never hidden by, say,
+/// a helper that needs updating.
+@MainActor
+@Observable
+final class VPhoneLaunchpadModel {
+ enum Section: String, CaseIterable, Identifiable {
+ case hostSetup
+ case coreBundle
+ case machines
+
+ var id: Self {
+ self
+ }
+
+ var title: String {
+ switch self {
+ case .hostSetup: "Host Setup"
+ case .coreBundle: "Core Bundle"
+ case .machines: "Machines"
+ }
+ }
+ }
+
+ let history = VPhoneLaunchpadCommandHistory()
+ let helper = VPhoneLaunchpadHelperClient()
+ let libraryRoot: URL
+ let host: VPhoneLaunchpadHostSetup
+ let bundles: VPhoneLaunchpadCoreBundle
+ let machines: VPhoneLaunchpadMachineLibrary
+
+ var selection: Section = .hostSetup
+ private(set) var isStarted = false
+
+ private static let setupCompletedKey = "VPhoneLaunchpadSetupCompleted"
+ private static let showAllSectionsKey = "VPhoneLaunchpadShowAllSections"
+
+ init() {
+ let environment = ProcessInfo.processInfo.environment["VPHONE_LIBRARY_ROOT"]
+ libraryRoot = environment.map { URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".vphone/machines", isDirectory: true)
+ host = VPhoneLaunchpadHostSetup(helper: helper, libraryRoot: libraryRoot)
+ bundles = VPhoneLaunchpadCoreBundle(helper: helper, history: history)
+ machines = VPhoneLaunchpadMachineLibrary(libraryRoot: libraryRoot, bundles: bundles, helper: helper)
+ }
+
+ // MARK: - Sections
+
+ private var setupCompleted: Bool {
+ get {
+ access(keyPath: \.setupCompleted)
+ return UserDefaults.standard.bool(forKey: Self.setupCompletedKey)
+ }
+ set {
+ withMutation(keyPath: \.setupCompleted) {
+ UserDefaults.standard.set(newValue, forKey: Self.setupCompletedKey)
+ }
+ }
+ }
+
+ var sections: [Section] {
+ #if DEBUG
+ if UserDefaults.standard.bool(forKey: Self.showAllSectionsKey) {
+ return Section.allCases
+ }
+ #endif
+ if setupCompleted {
+ return Section.allCases
+ }
+ var sections: [Section] = [.hostSetup]
+ if host.requiredPassed {
+ sections.append(.coreBundle)
+ if bundles.isReady {
+ sections.append(.machines)
+ }
+ }
+ return sections
+ }
+
+ func title(for section: Section) -> String {
+ switch section {
+ case .hostSetup where setupCompleted && !host.isChecking && !host.requiredPassed:
+ "\(section.title) ▲"
+ case .coreBundle where setupCompleted && !bundles.isReady && !bundles.installed.isEmpty:
+ "\(section.title) ▲"
+ default:
+ section.title
+ }
+ }
+
+ /// Installing a bundle needs the helper (root-owned store) and Developer
+ /// Tools access (the execution policy exception).
+ var canInstallBundles: Bool {
+ guard case .ready = helper.state else {
+ return false
+ }
+ return host.isDeveloperToolAuthorized && !bundles.isInstalling
+ }
+
+ // MARK: - Lifecycle
+
+ func start() async {
+ guard !isStarted else {
+ return
+ }
+ isStarted = true
+ await host.refresh()
+ await bundles.refresh()
+ await machines.refresh()
+ machines.startMonitoring()
+ advance(selectNewest: true)
+ }
+
+ func refreshHost() async {
+ await host.refresh()
+ advance(selectNewest: true)
+ }
+
+ func installBundle(_ release: VPhoneLaunchpadRelease) async {
+ await bundles.install(release)
+ await machines.refresh()
+ advance(selectNewest: false)
+ }
+
+ func removeBundle(_ version: String) async {
+ await bundles.remove(version)
+ if let active = bundles.activeVersion, bundles.active?.preflight == .pending {
+ await bundles.verify(active)
+ }
+ advance(selectNewest: false)
+ }
+
+ /// Records completed setup and moves the selection to a newly revealed
+ /// section, or back to one that still exists.
+ private func advance(selectNewest: Bool) {
+ let before = sections
+ if host.requiredPassed, bundles.isReady {
+ setupCompleted = true
+ }
+ let after = sections
+ if selectNewest || after.count > before.count || !after.contains(selection) {
+ selection = after.last ?? .hostSetup
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift
new file mode 100644
index 00000000..136350a4
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift
@@ -0,0 +1,61 @@
+import SwiftUI
+
+struct VPhoneLaunchpadRootView: View {
+ @Environment(VPhoneLaunchpadModel.self) private var model
+
+ var body: some View {
+ @Bindable var model = model
+ Group {
+ switch model.selection {
+ case .hostSetup:
+ VPhoneLaunchpadHostSetupView()
+ case .coreBundle:
+ VPhoneLaunchpadCoreBundleView()
+ case .machines:
+ VPhoneLaunchpadMachinesView()
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .toolbar {
+ ToolbarItem(placement: .principal) {
+ Picker("Section", selection: $model.selection) {
+ ForEach(model.sections) { section in
+ Text(model.title(for: section)).tag(section)
+ }
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .fixedSize()
+ }
+ }
+ .navigationTitle(model.selection.title)
+ .task { await model.start() }
+ .alert(
+ model.host.actionError?.message ?? "",
+ isPresented: errorBinding(\.host.actionError),
+ presenting: model.host.actionError,
+ ) { _ in
+ Button("OK") {}
+ } message: { error in
+ Text(error.detail ?? "")
+ }
+ .alert(
+ model.bundles.actionError?.message ?? "",
+ isPresented: errorBinding(\.bundles.actionError),
+ presenting: model.bundles.actionError,
+ ) { _ in
+ Button("OK") {}
+ } message: { error in
+ Text(error.detail ?? "")
+ }
+ }
+
+ private func errorBinding(
+ _ keyPath: ReferenceWritableKeyPath<VPhoneLaunchpadModel, VPhoneLaunchpadError?>,
+ ) -> Binding<Bool> {
+ Binding(
+ get: { model[keyPath: keyPath] != nil },
+ set: { if !$0 { model[keyPath: keyPath] = nil } },
+ )
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift
new file mode 100644
index 00000000..10205ecb
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift
@@ -0,0 +1,71 @@
+import SwiftUI
+
+// MARK: - Status
+
+nonisolated enum VPhoneLaunchpadStatus: Equatable, Sendable {
+ case passed
+ case warning
+ case failed
+ case pending
+ case running
+}
+
+/// The state of a check or step as the system draws it: an SF Symbol in its
+/// semantic colour, or a small spinner while work is in flight. Every state
+/// occupies the same square, so the triangle and the spinner do not push the
+/// text beside them out of line.
+struct VPhoneLaunchpadStatusIcon: View {
+ let status: VPhoneLaunchpadStatus
+
+ var body: some View {
+ symbol
+ .frame(width: 16, height: 16)
+ }
+
+ @ViewBuilder
+ private var symbol: some View {
+ switch status {
+ case .running:
+ ProgressView()
+ .controlSize(.mini)
+ case .passed:
+ Image(systemName: "checkmark.circle.fill").foregroundStyle(.green)
+ case .warning:
+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.yellow)
+ case .failed:
+ Image(systemName: "xmark.circle.fill").foregroundStyle(.red)
+ case .pending:
+ Image(systemName: "circle.dashed").foregroundStyle(.secondary)
+ }
+ }
+}
+
+// MARK: - Log
+
+/// Command output. The one place the app uses a monospaced face.
+struct VPhoneLaunchpadLogView: View {
+ let lines: [String]
+
+ var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView([.vertical, .horizontal]) {
+ LazyVStack(alignment: .leading, spacing: 1) {
+ ForEach(Array(lines.enumerated()), id: \.offset) { index, line in
+ Text(line)
+ .id(index)
+ }
+ }
+ .font(.system(.caption, design: .monospaced))
+ .textSelection(.enabled)
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .background(Color(nsColor: .textBackgroundColor))
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(.separator))
+ .onChange(of: lines.count) { _, count in
+ proxy.scrollTo(count - 1, anchor: .bottom)
+ }
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift
new file mode 100644
index 00000000..43fb0514
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift
@@ -0,0 +1,124 @@
+import Foundation
+
+/// A started child process whose merged stdout and stderr arrive line by line
+/// on a background thread.
+///
+/// Two output modes:
+/// - A pipe, for commands that finish. Output ends when every holder of the
+/// pipe has closed it.
+/// - A log file, for `vm launch`. The guest must outlive Launchpad: with a
+/// pipe, quitting the app would close the read end and the next line of
+/// guest serial output would kill the VM with SIGPIPE. The file is tailed
+/// while the app runs and stays behind as the machine's console log.
+nonisolated final class VPhoneLaunchpadChildProcess: @unchecked Sendable {
+ private let process = Process()
+ private let lock = NSLock()
+ private var exitStatus: Int32?
+ private var hasExited = false
+ private var waiters: [CheckedContinuation<Int32, Never>] = []
+
+ init(
+ executable: URL,
+ arguments: [String],
+ currentDirectory: URL? = nil,
+ logFile: URL? = nil,
+ onLine: @escaping @Sendable (String) -> Void,
+ ) throws {
+ process.executableURL = executable
+ process.arguments = arguments
+ if let currentDirectory {
+ process.currentDirectoryURL = currentDirectory
+ }
+ process.standardInput = FileHandle.nullDevice
+
+ if let logFile {
+ try FileManager.default.createDirectory(
+ at: logFile.deletingLastPathComponent(),
+ withIntermediateDirectories: true,
+ )
+ FileManager.default.createFile(atPath: logFile.path, contents: nil)
+ let writer = try FileHandle(forWritingTo: logFile)
+ process.standardOutput = writer
+ process.standardError = writer
+ process.terminationHandler = { [self] _ in
+ lock.withLock { hasExited = true }
+ }
+ try process.run()
+ try writer.close()
+ let reader = try FileHandle(forReadingFrom: logFile)
+ Thread.detachNewThread { [self] in
+ tail(reader, onLine)
+ }
+ } else {
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = pipe
+ try process.run()
+ let reader = pipe.fileHandleForReading
+ Thread.detachNewThread { [self] in
+ VPhoneLaunchpadLineReader.readLines(from: reader, onLine: onLine)
+ process.waitUntilExit()
+ finish(process.terminationStatus)
+ }
+ }
+ }
+
+ var isRunning: Bool {
+ lock.withLock { exitStatus == nil }
+ }
+
+ /// The exit status, once the process has exited and its output drained.
+ func wait() async -> Int32 {
+ await withCheckedContinuation { continuation in
+ lock.lock()
+ if let exitStatus {
+ lock.unlock()
+ continuation.resume(returning: exitStatus)
+ return
+ }
+ waiters.append(continuation)
+ lock.unlock()
+ }
+ }
+
+ /// SIGINT, which `vphone-cli` treats as a graceful stop.
+ func interrupt() {
+ if process.isRunning {
+ process.interrupt()
+ }
+ }
+
+ func terminate() {
+ if process.isRunning {
+ process.terminate()
+ }
+ }
+
+ private func tail(_ reader: FileHandle, _ onLine: (String) -> Void) {
+ var splitter = VPhoneLaunchpadLineSplitter()
+ while true {
+ let exited = lock.withLock { hasExited }
+ if let chunk = try? reader.readToEnd(), !chunk.isEmpty {
+ splitter.feed(chunk, onLine)
+ }
+ if exited {
+ break
+ }
+ Thread.sleep(forTimeInterval: 0.25)
+ }
+ splitter.flush(onLine)
+ try? reader.close()
+ finish(process.terminationStatus)
+ }
+
+ private func finish(_ status: Int32) {
+ lock.lock()
+ exitStatus = status
+ let pending = waiters
+ waiters = []
+ lock.unlock()
+ for waiter in pending {
+ waiter.resume(returning: status)
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift
new file mode 100644
index 00000000..5b17dcfd
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift
@@ -0,0 +1,178 @@
+import Foundation
+import Observation
+
+// MARK: - Errors
+
+nonisolated struct VPhoneLaunchpadError: LocalizedError {
+ let message: String
+ var detail: String?
+
+ init(_ message: String, detail: String? = nil) {
+ self.message = message
+ self.detail = detail
+ }
+
+ var errorDescription: String? {
+ message
+ }
+
+ var failureReason: String? {
+ detail
+ }
+}
+
+// MARK: - Result
+
+nonisolated struct VPhoneLaunchpadCommandResult: Sendable {
+ let status: Int32
+ let lines: [String]
+
+ var succeeded: Bool {
+ status == 0
+ }
+
+ /// The last few lines, which is where `vphone-cli` reports what failed.
+ var tail: String {
+ lines.suffix(12).joined(separator: "\n")
+ }
+
+ /// The last line that looks like a JSON document. stderr is merged into
+ /// the same stream, so warnings can precede it.
+ var jsonData: Data? {
+ lines.last { $0.hasPrefix("[") || $0.hasPrefix("{") }.map { Data($0.utf8) }
+ }
+}
+
+// MARK: - History
+
+/// Every command Launchpad runs, shown so it can be copied into a terminal.
+@MainActor
+@Observable
+final class VPhoneLaunchpadCommandHistory {
+ struct Entry: Identifiable {
+ let id = UUID()
+ let date = Date()
+ let text: String
+ var status: Int32?
+ }
+
+ private(set) var entries: [Entry] = []
+
+ func record(_ text: String) -> UUID {
+ let entry = Entry(text: text)
+ entries.append(entry)
+ if entries.count > 200 {
+ entries.removeFirst(entries.count - 200)
+ }
+ return entry.id
+ }
+
+ func finish(_ id: UUID, status: Int32) {
+ if let index = entries.firstIndex(where: { $0.id == id }) {
+ entries[index].status = status
+ }
+ }
+}
+
+// MARK: - vphone-cli
+
+/// Runs the active bundle's `vphone-cli` by absolute path. Nothing here goes
+/// through a shell or `$PATH`.
+@MainActor
+struct VPhoneLaunchpadCommandLine {
+ let executable: URL
+ let history: VPhoneLaunchpadCommandHistory
+
+ static func display(_ arguments: [String]) -> String {
+ (["vphone-cli"] + arguments.map(quoted)).joined(separator: " ")
+ }
+
+ private static func quoted(_ argument: String) -> String {
+ let plain = argument.allSatisfy { $0.isLetter || $0.isNumber || "-_./:=,@+".contains($0) }
+ return plain && !argument.isEmpty ? argument : "'\(argument.replacingOccurrences(of: "'", with: "'\\''"))'"
+ }
+
+ /// Runs to completion. Cancelling the calling task sends SIGINT.
+ func run(
+ _ arguments: [String],
+ recordInHistory: Bool = true,
+ onLine: (@MainActor @Sendable (String) -> Void)? = nil,
+ ) async throws -> VPhoneLaunchpadCommandResult {
+ let entry = recordInHistory ? history.record(Self.display(arguments)) : nil
+ let collector = VPhoneLaunchpadLineCollector()
+ let child = try VPhoneLaunchpadChildProcess(executable: executable, arguments: arguments) { line in
+ collector.append(line)
+ if let onLine {
+ DispatchQueue.main.async { MainActor.assumeIsolated { onLine(line) } }
+ }
+ }
+ let status = await withTaskCancellationHandler {
+ await child.wait()
+ } onCancel: {
+ child.interrupt()
+ }
+ if let entry {
+ history.finish(entry, status: status)
+ }
+ return VPhoneLaunchpadCommandResult(status: status, lines: collector.lines)
+ }
+
+ /// Runs to completion and throws with the output tail on a non-zero exit.
+ @discardableResult
+ func runChecked(
+ _ arguments: [String],
+ onLine: (@MainActor @Sendable (String) -> Void)? = nil,
+ ) async throws -> VPhoneLaunchpadCommandResult {
+ let result = try await run(arguments, onLine: onLine)
+ try Task.checkCancellation()
+ guard result.succeeded else {
+ throw VPhoneLaunchpadError(
+ "\(Self.display(arguments)) exited with status \(result.status).",
+ detail: result.tail,
+ )
+ }
+ return result
+ }
+
+ /// Starts a long-running command such as `vm launch` and returns at once.
+ /// Its output goes to `logFile`, so it outlives Launchpad.
+ func start(
+ _ arguments: [String],
+ logFile: URL,
+ onLine: @escaping @MainActor @Sendable (String) -> Void,
+ ) throws -> VPhoneLaunchpadChildProcess {
+ let entry = history.record(Self.display(arguments))
+ let child = try VPhoneLaunchpadChildProcess(
+ executable: executable,
+ arguments: arguments,
+ logFile: logFile,
+ ) { line in
+ DispatchQueue.main.async { MainActor.assumeIsolated { onLine(line) } }
+ }
+ let history = history
+ Task {
+ let status = await child.wait()
+ history.finish(entry, status: status)
+ }
+ return child
+ }
+}
+
+/// Collects output lines from the reader thread, keeping the most recent.
+nonisolated final class VPhoneLaunchpadLineCollector: @unchecked Sendable {
+ private let lock = NSLock()
+ private var storage: [String] = []
+
+ func append(_ line: String) {
+ lock.withLock {
+ storage.append(line)
+ if storage.count > 4000 {
+ storage.removeFirst(storage.count - 4000)
+ }
+ }
+ }
+
+ var lines: [String] {
+ lock.withLock { storage }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift
new file mode 100644
index 00000000..1cf3a389
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift
@@ -0,0 +1,289 @@
+import ExecutionPolicy
+import Foundation
+import Observation
+
+/// The second stage: installed VPhone.bundle versions, the one in use, and
+/// installing new ones from GitHub releases.
+@MainActor
+@Observable
+final class VPhoneLaunchpadCoreBundle {
+ // MARK: - Installed versions
+
+ struct Installed: Identifiable {
+ let receipt: VPhoneLaunchpadBundleReceipt
+ var policy: VPhoneLaunchpadStatus = .pending
+ var policyDetail = ""
+ var preflight: VPhoneLaunchpadStatus = .pending
+ var preflightDetail = ""
+
+ var id: String {
+ receipt.version
+ }
+
+ var version: String {
+ receipt.version
+ }
+ }
+
+ // MARK: - Install progress
+
+ enum InstallStep: CaseIterable, Identifiable {
+ case download
+ case verify
+ case install
+ case policy
+ case preflight
+
+ var id: Self {
+ self
+ }
+
+ var title: String {
+ switch self {
+ case .download: "Download"
+ case .verify: "Verify SHA-256"
+ case .install: "Install as root"
+ case .policy: "Add execution policy exception"
+ case .preflight: "Host preflight"
+ }
+ }
+ }
+
+ struct InstallProgress {
+ let release: VPhoneLaunchpadRelease
+ var steps: [InstallStep: VPhoneLaunchpadStatus] = [:]
+ var received: Int64 = 0
+ var error: VPhoneLaunchpadError?
+
+ func status(_ step: InstallStep) -> VPhoneLaunchpadStatus {
+ steps[step] ?? .pending
+ }
+ }
+
+ private(set) var installed: [Installed] = []
+ private(set) var releases: [VPhoneLaunchpadRelease] = []
+ private(set) var releasesError: String?
+ private(set) var progress: InstallProgress?
+ var actionError: VPhoneLaunchpadError?
+
+ private let helper: VPhoneLaunchpadHelperClient
+ private let history: VPhoneLaunchpadCommandHistory
+ private static let activeVersionKey = "VPhoneLaunchpadActiveBundleVersion"
+
+ init(helper: VPhoneLaunchpadHelperClient, history: VPhoneLaunchpadCommandHistory) {
+ self.helper = helper
+ self.history = history
+ }
+
+ // MARK: - Active version
+
+ var activeVersion: String? {
+ get {
+ access(keyPath: \.activeVersion)
+ let stored = UserDefaults.standard.string(forKey: Self.activeVersionKey)
+ if let stored, installed.contains(where: { $0.version == stored }) {
+ return stored
+ }
+ return installed.first?.version
+ }
+ set {
+ withMutation(keyPath: \.activeVersion) {
+ UserDefaults.standard.set(newValue, forKey: Self.activeVersionKey)
+ }
+ }
+ }
+
+ var active: Installed? {
+ installed.first { $0.version == activeVersion }
+ }
+
+ /// Machines appears once the active bundle has passed host preflight.
+ var isReady: Bool {
+ active?.preflight == .passed
+ }
+
+ var isInstalling: Bool {
+ guard let progress else {
+ return false
+ }
+ return progress.error == nil && progress.status(.preflight) != .passed
+ }
+
+ /// The newest release that is not installed yet, if it is newer than
+ /// everything installed.
+ var availableUpdate: VPhoneLaunchpadRelease? {
+ guard let latest = releases.first, !installed.contains(where: { $0.version == latest.version }) else {
+ return nil
+ }
+ return latest
+ }
+
+ func commandLine() -> VPhoneLaunchpadCommandLine? {
+ guard let version = activeVersion else {
+ return nil
+ }
+ return VPhoneLaunchpadCommandLine(
+ executable: VPhoneLaunchpadBundleStore.executable(version: version, named: "vphone-cli"),
+ history: history,
+ )
+ }
+
+ // MARK: - Refresh
+
+ func refresh() async {
+ loadInstalled()
+ if let version = activeVersion {
+ await verify(version)
+ }
+ await fetchReleases()
+ }
+
+ func fetchReleases() async {
+ do {
+ releases = try await VPhoneLaunchpadRelease.fetch()
+ releasesError = nil
+ } catch {
+ releasesError = error.localizedDescription
+ }
+ }
+
+ private func loadInstalled() {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: VPhoneLaunchpadBundleStore.root.path)) ?? []
+ let receipts = names
+ .filter(VPhoneLaunchpadNames.isValidVersion)
+ .compactMap(VPhoneLaunchpadBundleReceipt.load)
+ .sorted { $0.version.compare($1.version, options: .numeric) == .orderedDescending }
+ installed = receipts.map { receipt in
+ installed.first { $0.version == receipt.version && $0.receipt == receipt } ?? Installed(receipt: receipt)
+ }
+ }
+
+ /// Adds the execution policy exception and runs host preflight.
+ func verify(_ version: String) async {
+ update(version) {
+ $0.policy = .running
+ $0.preflight = .running
+ }
+ let bundle = VPhoneLaunchpadBundleStore.bundle(version: version)
+ do {
+ try EPExecutionPolicy().addException(for: bundle)
+ update(version) {
+ $0.policy = .passed
+ $0.policyDetail = "exception"
+ }
+ } catch {
+ update(version) {
+ $0.policy = .failed
+ $0.policyDetail = "no exception"
+ }
+ }
+
+ let commandLine = VPhoneLaunchpadCommandLine(
+ executable: VPhoneLaunchpadBundleStore.executable(version: version, named: "vphone-cli"),
+ history: history,
+ )
+ do {
+ let result = try await commandLine.run(["host", "preflight", "--quiet"])
+ update(version) {
+ $0.preflight = result.succeeded ? .passed : .failed
+ $0.preflightDetail = result.succeeded
+ ? "passed"
+ : (result.lines.last ?? "exit status \(result.status)")
+ .replacingOccurrences(of: "Error: ", with: "")
+ }
+ } catch {
+ update(version) {
+ $0.preflight = .failed
+ $0.preflightDetail = error.localizedDescription
+ }
+ }
+ }
+
+ private func update(_ version: String, _ change: (inout Installed) -> Void) {
+ if let index = installed.firstIndex(where: { $0.version == version }) {
+ change(&installed[index])
+ }
+ }
+
+ // MARK: - Install
+
+ func install(_ release: VPhoneLaunchpadRelease) async {
+ progress = InstallProgress(release: release)
+ var archive: URL?
+ defer {
+ if let archive {
+ try? FileManager.default.removeItem(at: archive.deletingLastPathComponent())
+ }
+ }
+ do {
+ set(.download, .running)
+ let (file, digest) = try await release.download { received in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated { self.progress?.received = received }
+ }
+ }
+ archive = file
+ set(.download, .passed)
+
+ set(.verify, .running)
+ guard digest == release.sha256.lowercased() else {
+ throw VPhoneLaunchpadError(
+ "The download does not match the published SHA-256.",
+ detail: "expected \(release.sha256)\nreceived \(digest)",
+ )
+ }
+ set(.verify, .passed)
+
+ set(.install, .running)
+ let handle = try FileHandle(forReadingFrom: file)
+ defer { try? handle.close() }
+ try await helper.installBundle(version: release.version, archive: handle, sha256: release.sha256)
+ set(.install, .passed)
+
+ loadInstalled()
+ activeVersion = release.version
+ set(.policy, .running)
+ set(.preflight, .running)
+ await verify(release.version)
+ let installed = installed.first { $0.version == release.version }
+ set(.policy, installed?.policy ?? .failed)
+ set(.preflight, installed?.preflight ?? .failed)
+ if installed?.preflight != .passed {
+ throw VPhoneLaunchpadError(
+ "Host preflight did not pass.",
+ detail: installed?.preflightDetail,
+ )
+ }
+ } catch {
+ for step in InstallStep.allCases where progress?.status(step) == .running {
+ set(step, .failed)
+ }
+ progress?.error = error as? VPhoneLaunchpadError
+ ?? VPhoneLaunchpadError("The install failed.", detail: error.localizedDescription)
+ }
+ }
+
+ func dismissProgress() {
+ progress = nil
+ }
+
+ private func set(_ step: InstallStep, _ status: VPhoneLaunchpadStatus) {
+ progress?.steps[step] = status
+ }
+
+ // MARK: - Use and remove
+
+ func use(_ version: String) async {
+ activeVersion = version
+ await verify(version)
+ }
+
+ func remove(_ version: String) async {
+ do {
+ try await helper.removeBundle(version: version)
+ } catch {
+ actionError = VPhoneLaunchpadError("VPhone.bundle \(version) could not be removed.", detail: "\(error)")
+ }
+ loadInstalled()
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swift
new file mode 100644
index 00000000..b7250469
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundleView.swift
@@ -0,0 +1,234 @@
+import SwiftUI
+
+struct VPhoneLaunchpadCoreBundleView: View {
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @State private var removal: String?
+
+ private var bundles: VPhoneLaunchpadCoreBundle {
+ model.bundles
+ }
+
+ private var notInstalled: [VPhoneLaunchpadRelease] {
+ bundles.releases.filter { release in !bundles.installed.contains { $0.version == release.version } }
+ }
+
+ var body: some View {
+ Form {
+ if let progress = bundles.progress {
+ progressSection(progress)
+ }
+ if bundles.installed.isEmpty {
+ latestSection
+ } else {
+ installedSection
+ if !notInstalled.isEmpty {
+ availableSection
+ }
+ }
+ Section {
+ LabeledContent("Location", value: VPhoneLaunchpadBundleStore.root.path)
+ LabeledContent("Owner", value: "root:wheel, written only by the helper")
+ } header: {
+ Text("Store")
+ } footer: {
+ if bundles.installed.isEmpty {
+ Text("Machines appears once a bundle is installed and passes host preflight.")
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ .formStyle(.grouped)
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ Button {
+ Task { await bundles.refresh() }
+ } label: {
+ Label("Check for Updates", systemImage: "arrow.clockwise")
+ }
+ .help("List releases again and rerun host preflight")
+ .disabled(bundles.isInstalling)
+ }
+ }
+ .confirmationDialog(
+ "Remove VPhone.bundle \(removal ?? "")?",
+ isPresented: Binding(get: { removal != nil }, set: { if !$0 { removal = nil } }),
+ ) {
+ Button("Remove", role: .destructive) {
+ if let version = removal {
+ Task { await model.removeBundle(version) }
+ }
+ }
+ } message: {
+ Text("Machines are not affected. You can install this version again later.")
+ }
+ }
+
+ // MARK: - Latest
+
+ @ViewBuilder
+ private var latestSection: some View {
+ Section("Latest Release") {
+ if let latest = bundles.releases.first {
+ releaseRow(latest, prominent: true)
+ } else if let error = bundles.releasesError {
+ Label(error, systemImage: "exclamationmark.triangle")
+ .foregroundStyle(.secondary)
+ } else {
+ HStack {
+ ProgressView().controlSize(.small)
+ Text("Loading releases…").foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+
+ // MARK: - Progress
+
+ private func progressSection(_ progress: VPhoneLaunchpadCoreBundle.InstallProgress) -> some View {
+ Section {
+ if progress.status(.download) == .running {
+ ProgressView(value: Double(progress.received), total: Double(max(progress.release.size, 1))) {
+ Text("Downloading")
+ } currentValueLabel: {
+ Text("\(Self.size(progress.received)) of \(Self.size(progress.release.size))")
+ }
+ }
+ ForEach(VPhoneLaunchpadCoreBundle.InstallStep.allCases) { step in
+ Label {
+ Text(step.title)
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: progress.status(step))
+ }
+ }
+ if let error = progress.error {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(error.message).foregroundStyle(.red)
+ if let detail = error.detail {
+ Text(detail)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ }
+ }
+ }
+ } header: {
+ HStack {
+ Text("Installing \(progress.release.version)")
+ Spacer()
+ if !bundles.isInstalling {
+ Button("Dismiss") { bundles.dismissProgress() }
+ .buttonStyle(.link)
+ }
+ }
+ }
+ }
+
+ // MARK: - Installed
+
+ private var installedSection: some View {
+ Section("Installed") {
+ ForEach(bundles.installed) { bundle in
+ installedRow(bundle)
+ }
+ }
+ }
+
+ private func installedRow(_ bundle: VPhoneLaunchpadCoreBundle.Installed) -> some View {
+ let isActive = bundle.version == bundles.activeVersion
+ return HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text("VPhone.bundle \(bundle.version)")
+ if isActive {
+ Text("Active")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ Text("Installed \(bundle.receipt.installedAt.formatted(date: .abbreviated, time: .omitted)) · SHA-256 \(Self.shortDigest(bundle.receipt.sha256))")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ Label {
+ Text(bundle.policy == .passed ? "Policy exception" : "No policy exception")
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: bundle.policy)
+ }
+ .font(.callout)
+ Label {
+ Text(bundle.preflight == .passed ? "Preflight passed" : bundle.preflightDetail.isEmpty ? "Preflight" : bundle.preflightDetail)
+ .lineLimit(1)
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: bundle.preflight)
+ }
+ .font(.callout)
+ .help(bundle.preflightDetail)
+ if !isActive {
+ Button("Use") { Task { await bundles.use(bundle.version) } }
+ }
+ Menu {
+ Button("Run Preflight Again") { Task { await bundles.verify(bundle.version) } }
+ Button("Show in Finder") {
+ NSWorkspace.shared.activateFileViewerSelecting([VPhoneLaunchpadBundleStore.bundle(version: bundle.version)])
+ }
+ Divider()
+ Button("Remove…", role: .destructive) { removal = bundle.version }
+ .disabled(bundles.isInstalling)
+ } label: {
+ Image(systemName: "ellipsis.circle")
+ }
+ .menuStyle(.borderlessButton)
+ .menuIndicator(.hidden)
+ .fixedSize()
+ }
+ }
+
+ // MARK: - Available
+
+ private var availableSection: some View {
+ Section("Available") {
+ ForEach(notInstalled) { release in
+ releaseRow(release, prominent: release == bundles.availableUpdate)
+ }
+ }
+ }
+
+ private func releaseRow(_ release: VPhoneLaunchpadRelease, prominent: Bool) -> some View {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text("VPhone.bundle \(release.version)")
+ if release.isPrerelease {
+ Text("Pre-release")
+ .font(.caption)
+ .foregroundStyle(.orange)
+ }
+ }
+ Text("\(release.publishedAt.formatted(date: .abbreviated, time: .omitted)) · \(Self.size(release.size)) · SHA-256 \(Self.shortDigest(release.sha256))")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer()
+ if prominent {
+ Button("Download and Install") { Task { await model.installBundle(release) } }
+ .buttonStyle(.borderedProminent)
+ .disabled(!model.canInstallBundles)
+ } else {
+ Button("Download and Install") { Task { await model.installBundle(release) } }
+ .disabled(!model.canInstallBundles)
+ }
+ }
+ .help(model.canInstallBundles ? "" : "Installing needs the privileged helper and Developer Tools access.")
+ }
+
+ // MARK: - Formatting
+
+ static func size(_ bytes: Int64) -> String {
+ ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
+ }
+
+ static func shortDigest(_ digest: String) -> String {
+ "\(digest.prefix(8))…"
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadRelease.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadRelease.swift
new file mode 100644
index 00000000..96e36928
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadRelease.swift
@@ -0,0 +1,116 @@
+import CryptoKit
+import Foundation
+
+/// A GitHub release that carries a `VPhone-<tag>.zip` asset. GitHub records a
+/// SHA-256 digest for every asset, which is what the download is checked
+/// against, here and again in the helper.
+nonisolated struct VPhoneLaunchpadRelease: Identifiable, Hashable, Sendable {
+ let version: String
+ let publishedAt: Date
+ let isPrerelease: Bool
+ let assetName: String
+ let downloadURL: URL
+ let size: Int64
+ let sha256: String
+
+ var id: String {
+ version
+ }
+
+ static let endpoint = URL(string: "https://api.github.com/repos/Lakr233/vphone-cli/releases?per_page=30")!
+
+ // MARK: - Listing
+
+ static func fetch() async throws -> [VPhoneLaunchpadRelease] {
+ var request = URLRequest(url: endpoint)
+ request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+ request.setValue("vphone-launchpad", forHTTPHeaderField: "User-Agent")
+ let (data, response) = try await URLSession.shared.data(for: request)
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
+ throw VPhoneLaunchpadError("GitHub answered the release list with an error.")
+ }
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ let payload = try decoder.decode([Payload].self, from: data)
+ return payload.compactMap { release in
+ guard !release.draft, VPhoneLaunchpadNames.isValidVersion(release.tag_name) else {
+ return nil
+ }
+ let asset = release.assets.first {
+ $0.name.range(of: "^VPhone-.+\\.zip$", options: .regularExpression) != nil
+ && ($0.digest ?? "").hasPrefix("sha256:")
+ }
+ guard let asset, let digest = asset.digest else {
+ return nil
+ }
+ return VPhoneLaunchpadRelease(
+ version: release.tag_name,
+ publishedAt: release.published_at ?? .distantPast,
+ isPrerelease: release.prerelease,
+ assetName: asset.name,
+ downloadURL: asset.browser_download_url,
+ size: asset.size,
+ sha256: String(digest.dropFirst("sha256:".count)),
+ )
+ }
+ .sorted { $0.publishedAt > $1.publishedAt }
+ }
+
+ private struct Payload: Decodable {
+ struct Asset: Decodable {
+ let name: String
+ let size: Int64
+ let digest: String?
+ let browser_download_url: URL
+ }
+
+ let tag_name: String
+ let draft: Bool
+ let prerelease: Bool
+ let published_at: Date?
+ let assets: [Asset]
+ }
+
+ // MARK: - Download
+
+ /// Downloads the asset into a fresh temporary directory, hashing as it
+ /// goes. Returns the file and its hex SHA-256.
+ @concurrent func download(progress: @escaping @Sendable (Int64) -> Void) async throws -> (URL, String) {
+ var request = URLRequest(url: downloadURL)
+ request.setValue("vphone-launchpad", forHTTPHeaderField: "User-Agent")
+ let (bytes, response) = try await URLSession.shared.bytes(for: request)
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
+ throw VPhoneLaunchpadError("The download of \(assetName) failed.")
+ }
+
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-launchpad-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let file = directory.appendingPathComponent(assetName)
+ FileManager.default.createFile(atPath: file.path, contents: nil)
+ let output = try FileHandle(forWritingTo: file)
+ defer { try? output.close() }
+
+ var hasher = SHA256()
+ var buffer = Data()
+ buffer.reserveCapacity(1 << 20)
+ var received: Int64 = 0
+ for try await byte in bytes {
+ buffer.append(byte)
+ if buffer.count >= 1 << 20 {
+ hasher.update(data: buffer)
+ try output.write(contentsOf: buffer)
+ received += Int64(buffer.count)
+ progress(received)
+ buffer.removeAll(keepingCapacity: true)
+ }
+ }
+ hasher.update(data: buffer)
+ try output.write(contentsOf: buffer)
+ received += Int64(buffer.count)
+ progress(received)
+
+ let digest = hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ return (file, digest)
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
new file mode 100644
index 00000000..c1858602
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
@@ -0,0 +1,291 @@
+import Foundation
+import Observation
+import Security
+import ServiceManagement
+
+/// Installs the privileged helper with SMJobBless and talks to it over XPC.
+@MainActor
+@Observable
+final class VPhoneLaunchpadHelperClient {
+ enum State: Equatable {
+ case unknown
+ case notInstalled
+ case outdated(installed: String, bundled: String)
+ case ready(String)
+ /// This build has no team in its requirements, so SMJobBless and the
+ /// XPC checks cannot succeed. See VPhoneLaunchpad.xcconfig.
+ case unconfigured
+ }
+
+ private(set) var state: State = .unknown
+ private var connection: NSXPCConnection?
+ private let receiver = VPhoneLaunchpadHelperReceiver()
+
+ nonisolated private static let label = VPhoneLaunchpadHelperIdentity.label
+
+ // MARK: - Status
+
+ /// CFBundleVersion of the helper embedded in this app.
+ var bundledVersion: String? {
+ let url = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LaunchServices/\(Self.label)")
+ let info = CFBundleCopyInfoDictionaryForURL(url as CFURL) as? [String: Any]
+ return info?["CFBundleVersion"] as? String
+ }
+
+ /// The requirement the app holds the helper to, from SMPrivilegedExecutables.
+ private var helperRequirement: String? {
+ let executables = Bundle.main.object(forInfoDictionaryKey: "SMPrivilegedExecutables") as? [String: String]
+ return executables?[Self.label]
+ }
+
+ var isConfigured: Bool {
+ guard let helperRequirement else {
+ return false
+ }
+ return !helperRequirement.contains("subject.OU] = \"\"")
+ }
+
+ func refresh() async {
+ guard isConfigured else {
+ state = .unconfigured
+ return
+ }
+ guard FileManager.default.fileExists(atPath: "/Library/LaunchDaemons/\(Self.label).plist") else {
+ state = .notInstalled
+ return
+ }
+ do {
+ let installed = try await version()
+ let bundled = bundledVersion ?? "?"
+ state = installed == bundled ? .ready(installed) : .outdated(installed: installed, bundled: bundled)
+ } catch {
+ state = .notInstalled
+ }
+ }
+
+ // MARK: - Install
+
+ /// Asks for an administrator and blesses the embedded helper.
+ func install() async throws {
+ guard isConfigured else {
+ throw VPhoneLaunchpadError(
+ "This build has no signing team.",
+ detail: "Set VPHONE_LAUNCHPAD_TEAM, rebuild, and sign the app before installing the helper.",
+ )
+ }
+ try await Task.detached { try Self.bless() }.value
+ connection?.invalidate()
+ connection = nil
+ await refresh()
+ }
+
+ func uninstall() async throws {
+ try await call { proxy, done in
+ proxy.uninstallHelper { message in done(message.map { VPhoneLaunchpadError($0) }) }
+ }
+ connection?.invalidate()
+ connection = nil
+ state = .notInstalled
+ }
+
+ nonisolated private static func bless() throws {
+ var authorization: AuthorizationRef?
+ var status = AuthorizationCreate(nil, nil, [], &authorization)
+ guard status == errAuthorizationSuccess, let authorization else {
+ throw VPhoneLaunchpadError("Cannot create an authorization (OSStatus \(status)).")
+ }
+ defer { AuthorizationFree(authorization, []) }
+
+ status = kSMRightBlessPrivilegedHelper.withCString { name in
+ var item = AuthorizationItem(name: name, valueLength: 0, value: nil, flags: 0)
+ return withUnsafeMutablePointer(to: &item) { pointer in
+ var rights = AuthorizationRights(count: 1, items: pointer)
+ return AuthorizationCopyRights(
+ authorization,
+ &rights,
+ nil,
+ [.interactionAllowed, .extendRights, .preAuthorize],
+ nil,
+ )
+ }
+ }
+ guard status == errAuthorizationSuccess else {
+ if status == errAuthorizationCanceled {
+ throw CancellationError()
+ }
+ throw VPhoneLaunchpadError("Administrator authorization failed (OSStatus \(status)).")
+ }
+
+ var error: Unmanaged<CFError>?
+ guard SMJobBless(kSMDomainSystemLaunchd, label as CFString, authorization, &error) else {
+ let reason = error.map { "\($0.takeRetainedValue())" } ?? "unknown error"
+ throw VPhoneLaunchpadError("The helper could not be installed.", detail: reason)
+ }
+ }
+
+ // MARK: - Calls
+
+ func version() async throws -> String {
+ try await withTimeout(seconds: 5) { proxy, done in
+ proxy.helperVersion { done(.success($0)) }
+ }
+ }
+
+ func installBundle(version: String, archive: FileHandle, sha256: String) async throws {
+ try await call { proxy, done in
+ proxy.installBundle(version: version, archive: archive, sha256: sha256) { message in
+ done(message.map { VPhoneLaunchpadError($0) })
+ }
+ }
+ }
+
+ func removeBundle(version: String) async throws {
+ try await call { proxy, done in
+ proxy.removeBundle(version: version) { message in done(message.map { VPhoneLaunchpadError($0) }) }
+ }
+ }
+
+ /// Runs `cfw install` as root. Output lines go to `onLine`.
+ func installCustomFirmware(
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ forceDyldSharedCacheMaxSlide: Bool,
+ keepArtifacts: Bool,
+ onLine: @escaping @MainActor @Sendable (String) -> Void,
+ ) async throws -> Int32 {
+ receiver.setHandler { line in
+ DispatchQueue.main.async { MainActor.assumeIsolated { onLine(line) } }
+ }
+ defer { receiver.setHandler(nil) }
+ return try await withTaskCancellationHandler {
+ try await request { proxy, done in
+ proxy.installCustomFirmware(
+ bundleVersion: bundleVersion,
+ machineName: machineName,
+ libraryRoot: libraryRoot,
+ forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,
+ keepArtifacts: keepArtifacts,
+ ) { status, message in
+ if let message {
+ done(.failure(VPhoneLaunchpadError(message)))
+ } else {
+ done(.success(status))
+ }
+ }
+ }
+ } onCancel: {
+ Task { @MainActor in self.cancelCustomFirmware() }
+ }
+ }
+
+ func cancelCustomFirmware() {
+ let proxy = currentConnection().remoteObjectProxy as? VPhoneLaunchpadHelperProtocol
+ proxy?.cancelCustomFirmware {}
+ }
+
+ // MARK: - XPC plumbing
+
+ private func currentConnection() -> NSXPCConnection {
+ if let connection {
+ return connection
+ }
+ let connection = NSXPCConnection(machServiceName: Self.label, options: .privileged)
+ connection.remoteObjectInterface = NSXPCInterface(with: VPhoneLaunchpadHelperProtocol.self)
+ connection.exportedInterface = NSXPCInterface(with: VPhoneLaunchpadHelperClientProtocol.self)
+ connection.exportedObject = receiver
+ if let helperRequirement {
+ connection.setCodeSigningRequirement(helperRequirement)
+ }
+ connection.invalidationHandler = { [weak self] in
+ Task { @MainActor in self?.connection = nil }
+ }
+ connection.resume()
+ self.connection = connection
+ return connection
+ }
+
+ /// One request whose reply carries a value.
+ private func request<T: Sendable>(
+ _ body: (VPhoneLaunchpadHelperProtocol, @escaping @Sendable (Result<T, Error>) -> Void) -> Void,
+ ) async throws -> T {
+ let connection = currentConnection()
+ return try await withCheckedThrowingContinuation { continuation in
+ let once = VPhoneLaunchpadResumeOnce(continuation)
+ let proxy = connection.remoteObjectProxyWithErrorHandler { error in
+ once.resume(.failure(error))
+ }
+ guard let helper = proxy as? VPhoneLaunchpadHelperProtocol else {
+ once.resume(.failure(VPhoneLaunchpadError("The helper connection has the wrong interface.")))
+ return
+ }
+ body(helper) { once.resume($0) }
+ }
+ }
+
+ /// One request whose reply carries only an optional error.
+ private func call(
+ _ body: (VPhoneLaunchpadHelperProtocol, @escaping @Sendable (Error?) -> Void) -> Void,
+ ) async throws {
+ let _: Bool = try await request { proxy, done in
+ body(proxy) { error in done(error.map { .failure($0) } ?? .success(true)) }
+ }
+ }
+
+ private func withTimeout<T: Sendable>(
+ seconds: Double,
+ _ body: @escaping (VPhoneLaunchpadHelperProtocol, @escaping @Sendable (Result<T, Error>) -> Void) -> Void,
+ ) async throws -> T {
+ let connection = currentConnection()
+ return try await withCheckedThrowingContinuation { continuation in
+ let once = VPhoneLaunchpadResumeOnce(continuation)
+ let proxy = connection.remoteObjectProxyWithErrorHandler { error in
+ once.resume(.failure(error))
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
+ once.resume(.failure(VPhoneLaunchpadError("The helper did not answer.")))
+ }
+ guard let helper = proxy as? VPhoneLaunchpadHelperProtocol else {
+ once.resume(.failure(VPhoneLaunchpadError("The helper connection has the wrong interface.")))
+ return
+ }
+ body(helper) { once.resume($0) }
+ }
+ }
+}
+
+// MARK: - Support
+
+/// Resumes a continuation exactly once, whichever of reply, error handler or
+/// timeout arrives first.
+nonisolated final class VPhoneLaunchpadResumeOnce<T: Sendable>: @unchecked Sendable {
+ private let lock = NSLock()
+ private var continuation: CheckedContinuation<T, Error>?
+
+ init(_ continuation: CheckedContinuation<T, Error>) {
+ self.continuation = continuation
+ }
+
+ func resume(_ result: Result<T, Error>) {
+ let pending: CheckedContinuation<T, Error>? = lock.withLock {
+ defer { continuation = nil }
+ return continuation
+ }
+ pending?.resume(with: result)
+ }
+}
+
+/// Receives output lines the helper streams back during a CFW install.
+nonisolated final class VPhoneLaunchpadHelperReceiver: NSObject, VPhoneLaunchpadHelperClientProtocol, @unchecked Sendable {
+ private let lock = NSLock()
+ private var handler: (@Sendable (String) -> Void)?
+
+ func setHandler(_ handler: (@Sendable (String) -> Void)?) {
+ lock.withLock { self.handler = handler }
+ }
+
+ func helperDidEmit(line: String) {
+ let handler = lock.withLock { self.handler }
+ handler?(line)
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swift
new file mode 100644
index 00000000..19775b40
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swift
@@ -0,0 +1,248 @@
+import Darwin
+import ExecutionPolicy
+import Foundation
+import Observation
+
+// MARK: - Check
+
+struct VPhoneLaunchpadHostCheck: Identifiable, Equatable {
+ enum Kind: String {
+ case appleSilicon
+ case macOS
+ case physicalMac
+ case libraryVolume
+ case developerTools
+ case helper
+ case diskSpace
+ case resources
+ case network
+ }
+
+ let kind: Kind
+ let title: String
+ let isRequired: Bool
+ var status: VPhoneLaunchpadStatus = .pending
+ var detail = ""
+
+ var id: Kind {
+ kind
+ }
+}
+
+// MARK: - Host setup
+
+/// The first stage. Required checks gate the Core Bundle section; advisory
+/// ones only warn.
+@MainActor
+@Observable
+final class VPhoneLaunchpadHostSetup {
+ private(set) var checks: [VPhoneLaunchpadHostCheck] = [
+ .init(kind: .appleSilicon, title: "Apple silicon", isRequired: true),
+ .init(kind: .macOS, title: "macOS 15 or later", isRequired: true),
+ .init(kind: .physicalMac, title: "Physical Mac", isRequired: true),
+ .init(kind: .libraryVolume, title: "Library on APFS", isRequired: true),
+ .init(kind: .developerTools, title: "Developer Tools access", isRequired: true),
+ .init(kind: .helper, title: "Privileged helper", isRequired: true),
+ .init(kind: .diskSpace, title: "Free disk space", isRequired: false),
+ .init(kind: .resources, title: "CPU and memory", isRequired: false),
+ .init(kind: .network, title: "Network", isRequired: false),
+ ]
+ private(set) var isChecking = false
+ var actionError: VPhoneLaunchpadError?
+
+ let helper: VPhoneLaunchpadHelperClient
+ let libraryRoot: URL
+
+ init(helper: VPhoneLaunchpadHelperClient, libraryRoot: URL) {
+ self.helper = helper
+ self.libraryRoot = libraryRoot
+ }
+
+ var required: [VPhoneLaunchpadHostCheck] {
+ checks.filter(\.isRequired)
+ }
+
+ var advisory: [VPhoneLaunchpadHostCheck] {
+ checks.filter { !$0.isRequired }
+ }
+
+ var requiredPassed: Bool {
+ required.allSatisfy { $0.status == .passed }
+ }
+
+ var passedRequiredCount: Int {
+ required.count(where: { $0.status == .passed })
+ }
+
+ var isDeveloperToolAuthorized: Bool {
+ EPDeveloperTool().authorizationStatus == .authorized
+ }
+
+ // MARK: - Checking
+
+ func refresh() async {
+ guard !isChecking else {
+ return
+ }
+ isChecking = true
+ defer { isChecking = false }
+
+ update(.appleSilicon, Self.appleSilicon())
+ update(.macOS, Self.macOSVersion())
+ update(.physicalMac, Self.physicalMac())
+ update(.libraryVolume, Self.libraryVolume(libraryRoot))
+ update(.developerTools, developerTools())
+ update(.helper, (.running, "Checking…"))
+ update(.diskSpace, Self.diskSpace(libraryRoot))
+ update(.resources, Self.resources())
+ update(.network, (.running, "Checking…"))
+
+ await helper.refresh()
+ update(.helper, helperStatus())
+ update(.network, await Self.network())
+ }
+
+ private func update(_ kind: VPhoneLaunchpadHostCheck.Kind, _ result: (VPhoneLaunchpadStatus, String)) {
+ guard let index = checks.firstIndex(where: { $0.kind == kind }) else {
+ return
+ }
+ checks[index].status = result.0
+ checks[index].detail = result.1
+ }
+
+ // MARK: - Actions
+
+ /// Opens Privacy & Security → Developer Tools with Launchpad listed.
+ func requestDeveloperTools() async {
+ _ = await EPDeveloperTool().requestAccess()
+ update(.developerTools, developerTools())
+ }
+
+ func installHelper() async {
+ update(.helper, (.running, "Waiting for an administrator…"))
+ do {
+ try await helper.install()
+ } catch is CancellationError {
+ } catch let error as VPhoneLaunchpadError {
+ actionError = error
+ } catch {
+ actionError = VPhoneLaunchpadError("The helper could not be installed.", detail: "\(error)")
+ }
+ update(.helper, helperStatus())
+ }
+
+ private func developerTools() -> (VPhoneLaunchpadStatus, String) {
+ switch EPDeveloperTool().authorizationStatus {
+ case .authorized:
+ (.passed, "Allowed")
+ case .denied:
+ (.failed, "Not allowed")
+ case .restricted:
+ (.failed, "Restricted by the system")
+ default:
+ (.pending, "Not requested")
+ }
+ }
+
+ private func helperStatus() -> (VPhoneLaunchpadStatus, String) {
+ switch helper.state {
+ case .unknown:
+ (.running, "Checking…")
+ case .notInstalled:
+ (.pending, "Not installed")
+ case let .outdated(installed, bundled):
+ (.pending, "Version \(installed) installed, \(bundled) available")
+ case let .ready(version):
+ (.passed, "Version \(version)")
+ case .unconfigured:
+ (.failed, "No signing team in this build")
+ }
+ }
+
+ // MARK: - Probes
+
+ nonisolated static func sysctlInt(_ name: String) -> Int? {
+ var value: Int32 = 0
+ var size = MemoryLayout<Int32>.size
+ guard sysctlbyname(name, &value, &size, nil, 0) == 0 else {
+ return nil
+ }
+ return Int(value)
+ }
+
+ nonisolated private static func appleSilicon() -> (VPhoneLaunchpadStatus, String) {
+ sysctlInt("hw.optional.arm64") == 1 ? (.passed, "arm64") : (.failed, "Intel Macs are not supported")
+ }
+
+ nonisolated private static func macOSVersion() -> (VPhoneLaunchpadStatus, String) {
+ let version = ProcessInfo.processInfo.operatingSystemVersion
+ let text = "\(version.majorVersion).\(version.minorVersion)"
+ return version.majorVersion >= 15 ? (.passed, text) : (.failed, "\(text) is too old")
+ }
+
+ nonisolated private static func physicalMac() -> (VPhoneLaunchpadStatus, String) {
+ let present = sysctlInt("kern.hv_vmm_present") ?? 0
+ return present == 0
+ ? (.passed, "kern.hv_vmm_present = 0")
+ : (.failed, "Running in a virtual machine")
+ }
+
+ nonisolated private static func libraryVolume(_ root: URL) -> (VPhoneLaunchpadStatus, String) {
+ let path = existingAncestor(of: root).path
+ var info = statfs()
+ guard statfs(path, &info) == 0 else {
+ return (.failed, "Cannot read the volume of \(abbreviated(root))")
+ }
+ let type = withUnsafeBytes(of: info.f_fstypename) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) }
+ return type == "apfs"
+ ? (.passed, abbreviated(root))
+ : (.failed, "\(abbreviated(root)) is on \(type)")
+ }
+
+ nonisolated private static func diskSpace(_ root: URL) -> (VPhoneLaunchpadStatus, String) {
+ let url = existingAncestor(of: root)
+ let values = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
+ guard let available = values?.volumeAvailableCapacityForImportantUsage else {
+ return (.warning, "Unknown")
+ }
+ let gigabytes = available / 1_000_000_000
+ return gigabytes >= 100
+ ? (.passed, "\(gigabytes) GB free")
+ : (.warning, "\(gigabytes) GB free, 100 GB recommended")
+ }
+
+ nonisolated private static func resources() -> (VPhoneLaunchpadStatus, String) {
+ let cores = ProcessInfo.processInfo.activeProcessorCount
+ let memory = ProcessInfo.processInfo.physicalMemory / (1 << 30)
+ let text = "\(cores) cores, \(memory) GB"
+ return cores >= 8 && memory >= 16 ? (.passed, text) : (.warning, "\(text); 8 cores, 16 GB recommended")
+ }
+
+ nonisolated private static func network() async -> (VPhoneLaunchpadStatus, String) {
+ let hosts = ["updates.cdn-apple.com", "api.github.com"]
+ var unreachable: [String] = []
+ for host in hosts {
+ var request = URLRequest(url: URL(string: "https://\(host)/")!)
+ request.httpMethod = "HEAD"
+ request.timeoutInterval = 6
+ if (try? await URLSession.shared.data(for: request)) == nil {
+ unreachable.append(host)
+ }
+ }
+ return unreachable.isEmpty
+ ? (.passed, hosts.joined(separator: ", "))
+ : (.warning, "Cannot reach \(unreachable.joined(separator: ", "))")
+ }
+
+ nonisolated static func existingAncestor(of url: URL) -> URL {
+ var candidate = url
+ while !FileManager.default.fileExists(atPath: candidate.path), candidate.path != "/" {
+ candidate.deleteLastPathComponent()
+ }
+ return candidate
+ }
+
+ nonisolated static func abbreviated(_ url: URL) -> String {
+ (url.path as NSString).abbreviatingWithTildeInPath
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swift
new file mode 100644
index 00000000..3a54b3f7
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swift
@@ -0,0 +1,98 @@
+import SwiftUI
+
+struct VPhoneLaunchpadHostSetupView: View {
+ @Environment(VPhoneLaunchpadModel.self) private var model
+
+ private var host: VPhoneLaunchpadHostSetup {
+ model.host
+ }
+
+ var body: some View {
+ Form {
+ Section {
+ ForEach(host.required) { check in
+ row(check)
+ }
+ } header: {
+ HStack {
+ Text("Required")
+ Spacer()
+ Text("\(host.passedRequiredCount) of \(host.required.count) passed")
+ .foregroundStyle(.secondary)
+ }
+ } footer: {
+ if !host.requiredPassed {
+ VStack(alignment: .leading, spacing: 4) {
+ if host.checks.contains(where: { $0.kind == .developerTools && $0.status != .passed }) {
+ Text("After allowing vphone-launchpad under Privacy & Security → Developer Tools, quit and reopen it.")
+ }
+ Text("Core Bundle appears once every required check passes.")
+ }
+ .foregroundStyle(.secondary)
+ }
+ }
+
+ Section {
+ ForEach(host.advisory) { check in
+ row(check)
+ }
+ } header: {
+ Text("Advisory")
+ } footer: {
+ Text("Advisory checks do not block setup.")
+ .foregroundStyle(.secondary)
+ }
+ }
+ .formStyle(.grouped)
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ Button {
+ Task { await model.refreshHost() }
+ } label: {
+ Label("Check Again", systemImage: "arrow.clockwise")
+ }
+ .help("Run every check again")
+ .disabled(host.isChecking)
+ }
+ }
+ }
+
+ /// Icon, title, then detail and any action pinned to the trailing edge.
+ /// A plain HStack rather than LabeledContent: LabeledContent splits the
+ /// row into columns and truncated the detail while leaving the button
+ /// short of the edge.
+ private func row(_ check: VPhoneLaunchpadHostCheck) -> some View {
+ HStack(spacing: 8) {
+ VPhoneLaunchpadStatusIcon(status: check.status)
+ Text(check.title)
+ .layoutPriority(1)
+ Spacer(minLength: 16)
+ Text(check.detail)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .help(check.detail)
+ action(for: check)
+ .fixedSize()
+ }
+ }
+
+ @ViewBuilder
+ private func action(for check: VPhoneLaunchpadHostCheck) -> some View {
+ switch check.kind {
+ case .developerTools where check.status != .passed:
+ Button("Open Settings") {
+ Task { await host.requestDeveloperTools() }
+ }
+ case .helper where check.status == .pending:
+ Button(host.helper.state == .notInstalled ? "Install…" : "Update…") {
+ Task {
+ await host.installHelper()
+ await model.refreshHost()
+ }
+ }
+ default:
+ EmptyView()
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
new file mode 100644
index 00000000..b400ada8
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
@@ -0,0 +1,423 @@
+import Darwin
+import Foundation
+import Observation
+
+/// `vm create`, one command at a time.
+///
+/// `vphone-cli vm create` runs the same stages in one process and asks for
+/// sudo partway through, which a GUI cannot answer. Running the stages here
+/// keeps every step visible and retryable, and keeps root to the one step
+/// that needs it: `cfw install`, run by the helper. The waits mirror
+/// VPhoneVirtualMachineCreator: the device identity file, 90 recovery probes,
+/// up to 30 seconds for the post-restore panic, 5 seconds before CFW, and up
+/// to 300 seconds for vphoned to answer on first boot.
+@MainActor
+@Observable
+final class VPhoneLaunchpadCreationPipeline {
+ struct Options: Sendable {
+ var name: String
+ var iphoneSource: String
+ var cloudOSSource: String
+ var cpuCount: Int
+ var memoryMB: Int
+ var diskSizeGB: Int
+ var network: String
+ var enableFrida: Bool
+ var forceDyldSharedCacheMaxSlide: Bool
+ var keepArtifacts: Bool
+ }
+
+ enum Step: Int, CaseIterable, Identifiable, Comparable {
+ case create
+ case prepare
+ case patch
+ case bootDFU
+ case waitDFU
+ case restore
+ case stopDFU
+ case installCFW
+ case firstBoot
+
+ var id: Int {
+ rawValue
+ }
+
+ static func < (lhs: Step, rhs: Step) -> Bool {
+ lhs.rawValue < rhs.rawValue
+ }
+
+ var title: String {
+ switch self {
+ case .create: "Create bundle"
+ case .prepare: "Download firmware"
+ case .patch: "Patch boot chain"
+ case .bootDFU: "Boot into DFU"
+ case .waitDFU: "Wait for DFU"
+ case .restore: "Restore"
+ case .stopDFU: "Stop VM"
+ case .installCFW: "Install CFW"
+ case .firstBoot: "First boot"
+ }
+ }
+
+ var needsRoot: Bool {
+ self == .installCFW
+ }
+ }
+
+ let options: Options
+ private(set) var statuses: [Step: VPhoneLaunchpadStatus] = [:]
+ private(set) var durations: [Step: TimeInterval] = [:]
+ private(set) var current: Step?
+ private(set) var log: [String] = []
+ private(set) var failure: VPhoneLaunchpadError?
+ private(set) var isRunning = false
+
+ private let libraryRoot: URL
+ private let bundles: VPhoneLaunchpadCoreBundle
+ private let helper: VPhoneLaunchpadHelperClient
+ private weak var library: VPhoneLaunchpadMachineLibrary?
+ private var task: Task<Void, Never>?
+ private var dfu: VPhoneLaunchpadChildProcess?
+ private var dfuLines: [String] = []
+
+ nonisolated static let panicPattern = #"(^|[^p])(panic|kernel panic|panic\.apple\.com|stackshot succeeded)"#
+
+ init(
+ options: Options,
+ libraryRoot: URL,
+ bundles: VPhoneLaunchpadCoreBundle,
+ helper: VPhoneLaunchpadHelperClient,
+ library: VPhoneLaunchpadMachineLibrary,
+ ) {
+ self.options = options
+ self.libraryRoot = libraryRoot
+ self.bundles = bundles
+ self.helper = helper
+ self.library = library
+ }
+
+ var isFinished: Bool {
+ statuses[.firstBoot] == .passed
+ }
+
+ func status(_ step: Step) -> VPhoneLaunchpadStatus {
+ statuses[step] ?? .pending
+ }
+
+ /// The step a retry starts from: the one that failed.
+ var failedStep: Step? {
+ Step.allCases.first { statuses[$0] == .failed }
+ }
+
+ func command(for step: Step) -> String {
+ let name = options.name
+ return switch step {
+ case .create: "vm new \(name) --cpu \(options.cpuCount) --memory \(options.memoryMB) --disk-size \(options.diskSizeGB)"
+ case .prepare: "fw prepare \(name)"
+ case .patch: "fw patch \(name)" + (options.enableFrida ? " --frida" : "")
+ case .bootDFU: "vm launch \(name) --dfu"
+ case .waitDFU: "recovery-probe --ecid …"
+ case .restore: "restore \(name)"
+ case .stopDFU: "vm stop \(name)"
+ case .installCFW: "cfw install \(name)"
+ case .firstBoot: "vm launch \(name)"
+ }
+ }
+
+ // MARK: - Control
+
+ func start(from first: Step = .create) {
+ guard !isRunning else {
+ return
+ }
+ failure = nil
+ for step in Step.allCases where step >= first {
+ statuses[step] = .pending
+ durations[step] = nil
+ }
+ isRunning = true
+ task = Task { await run(from: first) }
+ }
+
+ func cancel() {
+ task?.cancel()
+ }
+
+ private func run(from first: Step) async {
+ defer {
+ isRunning = false
+ current = nil
+ dfu?.terminate()
+ dfu = nil
+ }
+ for step in Step.allCases where step >= first {
+ current = step
+ statuses[step] = .running
+ let began = Date()
+ do {
+ try await perform(step)
+ try Task.checkCancellation()
+ statuses[step] = .passed
+ durations[step] = Date().timeIntervalSince(began)
+ } catch {
+ statuses[step] = .failed
+ durations[step] = Date().timeIntervalSince(began)
+ if error is CancellationError || Task.isCancelled {
+ failure = VPhoneLaunchpadError("Cancelled during \(step.title.lowercased()).")
+ } else {
+ failure = error as? VPhoneLaunchpadError
+ ?? VPhoneLaunchpadError("\(step.title) failed.", detail: error.localizedDescription)
+ }
+ append("✕ \(failure?.message ?? step.title)")
+ await library?.refresh()
+ return
+ }
+ }
+ append("● \(options.name) is ready.")
+ }
+
+ private func append(_ line: String) {
+ log.append(line)
+ if log.count > 3000 {
+ log.removeFirst(log.count - 3000)
+ }
+ }
+
+ // MARK: - Steps
+
+ private func perform(_ step: Step) async throws {
+ guard let commandLine = bundles.commandLine() else {
+ throw VPhoneLaunchpadError("No core bundle is active.")
+ }
+ let name = options.name
+ let library = ["--library-root", libraryRoot.path]
+ let machine = libraryRoot.appendingPathComponent(name, isDirectory: true)
+ let output: @MainActor @Sendable (String) -> Void = { [weak self] line in self?.append(line) }
+
+ func run(_ arguments: [String]) async throws {
+ append("$ \(VPhoneLaunchpadCommandLine.display(arguments))")
+ try await commandLine.runChecked(arguments, onLine: output)
+ }
+
+ switch step {
+ case .create:
+ try await run(["vm", "new", name, "--cpu", String(options.cpuCount),
+ "--memory", String(options.memoryMB), "--disk-size", String(options.diskSizeGB)] + library)
+ if options.network != "nat" {
+ try await run(["vm", "config", name, "--network", options.network] + library)
+ }
+ await self.library?.refresh()
+
+ case .prepare:
+ try await run(["fw", "prepare", name, "--iphone-source", options.iphoneSource,
+ "--cloudos-source", options.cloudOSSource] + library)
+
+ case .patch:
+ try await run(["fw", "patch", name] + (options.enableFrida ? ["--frida"] : []) + library)
+
+ case .bootDFU:
+ let arguments = ["vm", "launch", name, "--dfu"] + library
+ append("$ \(VPhoneLaunchpadCommandLine.display(arguments))")
+ dfuLines = []
+ dfu = try commandLine.start(
+ arguments,
+ logFile: VPhoneLaunchpadMachineLibrary.consoleLog(name, suffix: "-dfu"),
+ ) { [weak self] line in
+ self?.dfuLines.append(line)
+ self?.append("dfu \(line)")
+ }
+ let identity = machine.appendingPathComponent("udid-prediction.txt")
+ for _ in 0 ..< 30 {
+ if FileManager.default.fileExists(atPath: identity.path) {
+ return
+ }
+ try requireDFURunning()
+ try await Task.sleep(for: .seconds(1))
+ }
+ throw VPhoneLaunchpadError("The DFU boot did not write udid-prediction.txt within 30 seconds.")
+
+ case .waitDFU:
+ let ecid = try Self.ecid(in: machine)
+ append("$ vphone-cli recovery-probe --ecid \(ecid) --timeout 2 (up to 90 attempts)")
+ for attempt in 1 ... 90 {
+ try Task.checkCancellation()
+ try requireDFURunning()
+ let result = try await commandLine.run(
+ ["recovery-probe", "--ecid", ecid, "--timeout", "2"],
+ recordInHistory: attempt == 1,
+ )
+ if result.succeeded {
+ append("device endpoint is reachable")
+ return
+ }
+ try await Task.sleep(for: .seconds(2))
+ }
+ throw VPhoneLaunchpadError("Timed out waiting for the device to enter recovery mode.")
+
+ case .restore:
+ try requireDFURunning()
+ try await run(["restore", name] + library)
+
+ case .stopDFU:
+ append("waiting up to 30s for the post-restore reboot")
+ for _ in 0 ..< 30 {
+ if dfu?.isRunning != true || dfuLines.contains(where: Self.isPanic) {
+ break
+ }
+ try await Task.sleep(for: .seconds(1))
+ }
+ try await run(["vm", "stop", name, "--timeout", "20"] + library)
+ dfu?.terminate()
+ dfu = nil
+ append("waiting 5s for cleanup before CFW install")
+ try await Task.sleep(for: .seconds(5))
+
+ case .installCFW:
+ guard let version = bundles.activeVersion else {
+ throw VPhoneLaunchpadError("No core bundle is active.")
+ }
+ let status = try await helper.installCustomFirmware(
+ bundleVersion: version,
+ machineName: name,
+ libraryRoot: Self.canonicalPath(libraryRoot),
+ forceDyldSharedCacheMaxSlide: options.forceDyldSharedCacheMaxSlide,
+ keepArtifacts: options.keepArtifacts,
+ onLine: output,
+ )
+ guard status == 0 else {
+ throw VPhoneLaunchpadError("cfw install exited with status \(status).", detail: log.suffix(12).joined(separator: "\n"))
+ }
+
+ case .firstBoot:
+ try await firstBoot(name: name, machine: machine)
+ }
+ }
+
+ /// Boots with a window, as `vm create` does, and waits for vphoned to
+ /// answer on the VM's automation socket. The machine keeps running.
+ private func firstBoot(name: String, machine: URL) async throws {
+ guard let library else {
+ return
+ }
+ append("$ vphone-cli vm launch \(name)")
+ library.start(name)
+ guard let child = library.launchedProcess(name) else {
+ throw VPhoneLaunchpadError("\(name) could not be started.")
+ }
+ let socket = machine.appendingPathComponent("vphone.sock").path
+ append("waiting up to 300s for vphoned")
+ for _ in 0 ..< 300 {
+ try Task.checkCancellation()
+ if (library.consoles[name] ?? []).contains(where: Self.isPanic) {
+ throw VPhoneLaunchpadError("The guest panicked on first boot.", detail: "See the machine's console.")
+ }
+ guard child.isRunning else {
+ throw VPhoneLaunchpadError("The VM exited before vphoned answered.")
+ }
+ if await Task.detached(operation: { Self.ping(socketPath: socket) }).value {
+ append("vphoned answered")
+ return
+ }
+ try await Task.sleep(for: .seconds(1))
+ }
+ throw VPhoneLaunchpadError("vphoned did not answer within 300 seconds.")
+ }
+
+ private func requireDFURunning() throws {
+ guard dfu?.isRunning == true else {
+ throw VPhoneLaunchpadError("The DFU boot exited.", detail: dfuLines.suffix(12).joined(separator: "\n"))
+ }
+ }
+
+ // MARK: - Helpers
+
+ nonisolated static func isPanic(_ line: String) -> Bool {
+ line.range(of: panicPattern, options: [.regularExpression, .caseInsensitive]) != nil
+ }
+
+ /// The ECID the DFU boot wrote into udid-prediction.txt.
+ nonisolated static func ecid(in machine: URL) throws -> String {
+ let text = (try? String(contentsOf: machine.appendingPathComponent("udid-prediction.txt"), encoding: .utf8)) ?? ""
+ var udid = ""
+ for line in text.split(whereSeparator: \.isNewline) {
+ let pair = line.split(separator: "=", maxSplits: 1).map(String.init)
+ guard pair.count == 2 else {
+ continue
+ }
+ if pair[0] == "ECID", !pair[1].isEmpty {
+ return pair[1]
+ }
+ if pair[0] == "UDID" {
+ udid = pair[1]
+ }
+ }
+ if let suffix = udid.split(separator: "-", maxSplits: 1).last, udid.contains("-") {
+ return String(suffix)
+ }
+ throw VPhoneLaunchpadError("udid-prediction.txt has no ECID.")
+ }
+
+ nonisolated static func canonicalPath(_ url: URL) -> String {
+ guard let resolved = realpath(url.path, nil) else {
+ return url.path
+ }
+ defer { free(resolved) }
+ return String(cString: resolved)
+ }
+
+ /// The probe `vm create` uses: a ping over vphone.sock that vphoned
+ /// answers with `"ok": true`.
+ nonisolated static func ping(socketPath: String) -> Bool {
+ let path = socketPath.utf8CString
+ var address = sockaddr_un()
+ guard path.count <= MemoryLayout.size(ofValue: address.sun_path) else {
+ return false
+ }
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutablePointer(to: &address.sun_path) { pointer in
+ pointer.withMemoryRebound(to: CChar.self, capacity: path.count) { destination in
+ for (index, byte) in path.enumerated() {
+ destination[index] = byte
+ }
+ }
+ }
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else {
+ return false
+ }
+ defer { close(fd) }
+ var timeout = timeval(tv_sec: 2, tv_usec: 0)
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
+ var noSigPipe: Int32 = 1
+ setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout<Int32>.size))
+ let connected = withUnsafePointer(to: &address) { pointer in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ guard connected == 0 else {
+ return false
+ }
+ let request = Data("{\"t\":\"ping\",\"screen\":false}\n".utf8)
+ let written = request.withUnsafeBytes { write(fd, $0.baseAddress, $0.count) }
+ guard written == request.count else {
+ return false
+ }
+ var reply = Data()
+ var buffer = [UInt8](repeating: 0, count: 512)
+ while reply.count < 4096 {
+ let count = buffer.withUnsafeMutableBytes { read(fd, $0.baseAddress, $0.count) }
+ guard count > 0 else {
+ return false
+ }
+ reply.append(contentsOf: buffer.prefix(count))
+ if let newline = reply.firstIndex(of: 0x0A),
+ let json = try? JSONSerialization.jsonObject(with: Data(reply[..<newline])) as? [String: Any]
+ {
+ return json["ok"] as? Bool == true
+ }
+ }
+ return false
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
new file mode 100644
index 00000000..90d6b1da
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
@@ -0,0 +1,74 @@
+import Foundation
+
+// MARK: - vm list / vm info
+
+/// Mirrors `VPhoneBundleReport`, the JSON `vphone-cli vm list --json` and
+/// `vm info --json` print.
+nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Sendable {
+ struct Network: Decodable, Hashable, Sendable {
+ let mode: String
+ let macAddress: String
+ let bridgeInterface: String?
+ }
+
+ struct OSVersion: Decodable, Hashable, Sendable {
+ let version: String
+ let build: String
+ }
+
+ struct RestoreInfo: Decodable, Hashable, Sendable {
+ let ios: OSVersion
+ let cloudOS: OSVersion
+ let variant: String?
+ let device: String?
+ }
+
+ let name: String
+ let cpuCount: Int
+ let memoryMB: Int
+ let diskSizeBytes: Int64
+ let network: Network
+ let restoreInfo: RestoreInfo?
+ let udid: String?
+
+ var id: String {
+ name
+ }
+
+ var networkDescription: String {
+ switch network.mode {
+ case "nat": "NAT"
+ case "bridged": "bridged" + (network.bridgeInterface.map { " to \($0)" } ?? "")
+ case "hostOnly": "host only"
+ default: "none"
+ }
+ }
+}
+
+// MARK: - fw catalog
+
+/// Mirrors `VPhoneFirmwareCatalogReport` from `vphone-cli fw catalog --json`.
+nonisolated struct VPhoneLaunchpadFirmwareCatalog: Decodable, Sendable {
+ struct Image: Decodable, Hashable, Sendable {
+ let name: String
+ let url: String
+ }
+
+ struct Pairing: Decodable, Hashable, Identifiable, Sendable {
+ let ios: Image
+ let recommendedCloudOS: Image
+
+ var id: String {
+ ios.url
+ }
+
+ /// The build from an IPSW name such as `iPhone17,3_27.0_24A435_Restore.ipsw`.
+ var build: String {
+ let fields = (ios.url as NSString).lastPathComponent.split(separator: "_")
+ return fields.count >= 4 ? String(fields[2]) : ""
+ }
+ }
+
+ let device: String
+ let pairings: [Pairing]
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
new file mode 100644
index 00000000..ab406c12
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -0,0 +1,310 @@
+import Foundation
+import Observation
+
+/// The third stage: the VM library, driven entirely through `vphone-cli vm`.
+@MainActor
+@Observable
+final class VPhoneLaunchpadMachineLibrary {
+ enum RunState: Equatable {
+ case stopped
+ case running
+ case busy(String)
+ }
+
+ private(set) var machines: [VPhoneLaunchpadMachine] = []
+ private(set) var listError: String?
+ private(set) var startedAt: [String: Date] = [:]
+ private(set) var consoles: [String: [String]] = [:]
+ private(set) var creations: [String: VPhoneLaunchpadCreationPipeline] = [:]
+ private(set) var globalActivity: String?
+ var selection: String?
+ var actionError: VPhoneLaunchpadError?
+
+ let libraryRoot: URL
+ private let bundles: VPhoneLaunchpadCoreBundle
+ private let helper: VPhoneLaunchpadHelperClient
+ private var launched: [String: VPhoneLaunchpadChildProcess] = [:]
+ private var externallyRunning: Set<String> = []
+ private var activities: [String: String] = [:]
+ private var isRefreshing = false
+ private var timer: Timer?
+
+ init(libraryRoot: URL, bundles: VPhoneLaunchpadCoreBundle, helper: VPhoneLaunchpadHelperClient) {
+ self.libraryRoot = libraryRoot
+ self.bundles = bundles
+ self.helper = helper
+ }
+
+ var libraryArguments: [String] {
+ ["--library-root", libraryRoot.path]
+ }
+
+ var selected: VPhoneLaunchpadMachine? {
+ machines.first { $0.name == selection }
+ }
+
+ var runningCount: Int {
+ machines.count(where: { state(of: $0.name) == .running })
+ }
+
+ var hasActiveCreation: Bool {
+ creations.values.contains(where: \.isRunning)
+ }
+
+ func state(of name: String) -> RunState {
+ if let creation = creations[name], creation.isRunning, let step = creation.current {
+ return .busy("creating: \(step.title.lowercased())")
+ }
+ if let activity = activities[name] {
+ return .busy(activity)
+ }
+ if launched[name]?.isRunning == true || externallyRunning.contains(name) {
+ return .running
+ }
+ return .stopped
+ }
+
+ func launchedProcess(_ name: String) -> VPhoneLaunchpadChildProcess? {
+ launched[name]
+ }
+
+ // MARK: - Refresh
+
+ func startMonitoring() {
+ guard timer == nil else {
+ return
+ }
+ timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
+ Task { @MainActor in await self?.refresh() }
+ }
+ }
+
+ func refresh() async {
+ guard let commandLine = bundles.commandLine(), !isRefreshing else {
+ return
+ }
+ isRefreshing = true
+ defer { isRefreshing = false }
+ do {
+ let result = try await commandLine.run(["vm", "list", "--json"] + libraryArguments, recordInHistory: false)
+ if result.succeeded, let data = result.jsonData {
+ machines = try JSONDecoder().decode([VPhoneLaunchpadMachine].self, from: data)
+ listError = nil
+ } else {
+ listError = result.tail
+ }
+ } catch {
+ listError = error.localizedDescription
+ }
+ if selection == nil || !machines.contains(where: { $0.name == selection }) {
+ selection = machines.first?.name
+ }
+ let root = libraryRoot
+ let names = machines.map(\.name)
+ externallyRunning = await Task.detached { Self.machinesHoldingDisks(root: root, names: names) }.value
+ }
+
+ /// The same test `vm stop` uses: a machine runs while some process holds
+ /// its disk image open. This also finds guests started outside Launchpad.
+ nonisolated private static func machinesHoldingDisks(root: URL, names: [String]) -> Set<String> {
+ var diskOwners: [String: String] = [:]
+ for name in names {
+ let bundle = root.appendingPathComponent(name, isDirectory: true)
+ let manifest = NSDictionary(contentsOf: bundle.appendingPathComponent("config.plist"))
+ let disk = manifest?["diskImage"] as? String ?? "Disk.img"
+ diskOwners[bundle.appendingPathComponent(disk).path] = name
+ }
+ guard !diskOwners.isEmpty else {
+ return []
+ }
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
+ process.arguments = ["-F", "n", "--"] + diskOwners.keys.sorted()
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = FileHandle.nullDevice
+ guard (try? process.run()) != nil else {
+ return []
+ }
+ let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ process.waitUntilExit()
+ var running: Set<String> = []
+ for line in output.split(separator: "\n") where line.hasPrefix("n") {
+ if let name = diskOwners[String(line.dropFirst())] {
+ running.insert(name)
+ }
+ }
+ return running
+ }
+
+ // MARK: - Console
+
+ static func consoleLog(_ name: String, suffix: String = "") -> URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Logs/vphone-launchpad", isDirectory: true)
+ .appendingPathComponent("\(name)\(suffix).log")
+ }
+
+ func appendConsole(_ name: String, _ line: String) {
+ var lines = consoles[name] ?? []
+ lines.append(line)
+ if lines.count > 500 {
+ lines.removeFirst(lines.count - 500)
+ }
+ consoles[name] = lines
+ }
+
+ /// Shows the tail of a previous session's console log for a machine that
+ /// Launchpad did not start in this session.
+ func loadConsoleIfNeeded(_ name: String) {
+ guard consoles[name] == nil,
+ let handle = try? FileHandle(forReadingFrom: Self.consoleLog(name))
+ else {
+ return
+ }
+ defer { try? handle.close() }
+ let size = (try? handle.seekToEnd()) ?? 0
+ try? handle.seek(toOffset: size > 65536 ? size - 65536 : 0)
+ var lines: [String] = []
+ var splitter = VPhoneLaunchpadLineSplitter()
+ splitter.feed((try? handle.readToEnd()) ?? Data()) { lines.append($0) }
+ splitter.flush { lines.append($0) }
+ consoles[name] = Array(lines.suffix(200))
+ }
+
+ // MARK: - Start and stop
+
+ func start(_ name: String, headless: Bool = false) {
+ guard let commandLine = bundles.commandLine() else {
+ return
+ }
+ var arguments = ["vm", "launch", name] + libraryArguments
+ if headless {
+ arguments.append("--headless")
+ }
+ consoles[name] = []
+ do {
+ let child = try commandLine.start(arguments, logFile: Self.consoleLog(name)) { [weak self] line in
+ self?.appendConsole(name, line)
+ }
+ launched[name] = child
+ startedAt[name] = Date()
+ Task {
+ let status = await child.wait()
+ if launched[name] === child {
+ launched[name] = nil
+ startedAt[name] = nil
+ }
+ appendConsole(name, "vm launch exited with status \(status)")
+ await refresh()
+ }
+ } catch {
+ actionError = VPhoneLaunchpadError("\(name) could not be started.", detail: error.localizedDescription)
+ }
+ }
+
+ func stop(_ name: String) async {
+ await perform("stopping", on: name, ["vm", "stop", name] + libraryArguments)
+ launched[name]?.interrupt()
+ }
+
+ // MARK: - Edits
+
+ func configure(_ name: String, cpu: Int?, memoryMB: Int?, network: String?, bridgeInterface: String?) async {
+ var arguments = ["vm", "config", name] + libraryArguments
+ if let cpu {
+ arguments += ["--cpu", String(cpu)]
+ }
+ if let memoryMB {
+ arguments += ["--memory", String(memoryMB)]
+ }
+ if let network {
+ arguments += ["--network", network]
+ }
+ if let bridgeInterface, !bridgeInterface.isEmpty {
+ arguments += ["--bridge-interface", bridgeInterface]
+ }
+ await perform("saving settings", on: name, arguments)
+ }
+
+ func rename(_ name: String, to newName: String) async {
+ if await perform("renaming", on: name, ["vm", "rename", name, newName] + libraryArguments) {
+ selection = newName
+ }
+ }
+
+ func clone(_ name: String, as newName: String) async {
+ if await perform("cloning", on: name, ["vm", "clone", name, newName] + libraryArguments) {
+ selection = newName
+ }
+ }
+
+ func delete(_ name: String) async {
+ await perform("deleting", on: name, ["vm", "delete", name, "--force"] + libraryArguments)
+ }
+
+ func export(_ name: String, to destination: URL, densest: Bool, includeIPSW: Bool) async {
+ var arguments = ["vm", "export", name, "--out", destination.path] + libraryArguments
+ if densest {
+ arguments.append("--max")
+ }
+ if includeIPSW {
+ arguments.append("--include-ipsw")
+ }
+ await perform("exporting", on: name, arguments)
+ }
+
+ func importArchive(_ archive: URL) async {
+ await perform("Importing \(archive.lastPathComponent)", on: nil, ["vm", "import", archive.path] + libraryArguments)
+ }
+
+ @discardableResult
+ private func perform(_ activity: String, on name: String?, _ arguments: [String]) async -> Bool {
+ guard let commandLine = bundles.commandLine() else {
+ return false
+ }
+ if let name {
+ activities[name] = activity
+ } else {
+ globalActivity = activity
+ }
+ defer {
+ if let name {
+ activities[name] = nil
+ } else {
+ globalActivity = nil
+ }
+ }
+ do {
+ try await commandLine.runChecked(arguments)
+ await refresh()
+ return true
+ } catch {
+ actionError = error as? VPhoneLaunchpadError
+ ?? VPhoneLaunchpadError("The command failed.", detail: error.localizedDescription)
+ await refresh()
+ return false
+ }
+ }
+
+ // MARK: - Create
+
+ func create(_ options: VPhoneLaunchpadCreationPipeline.Options) -> VPhoneLaunchpadCreationPipeline {
+ let pipeline = VPhoneLaunchpadCreationPipeline(
+ options: options,
+ libraryRoot: libraryRoot,
+ bundles: bundles,
+ helper: helper,
+ library: self,
+ )
+ creations[options.name] = pipeline
+ pipeline.start()
+ return pipeline
+ }
+
+ func discardCreation(_ name: String) {
+ if creations[name]?.isRunning == false {
+ creations[name] = nil
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
new file mode 100644
index 00000000..674eb939
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
@@ -0,0 +1,164 @@
+import AppKit
+import SwiftUI
+
+// MARK: - Settings
+
+struct VPhoneLaunchpadMachineSettingsView: View {
+ let machine: VPhoneLaunchpadMachine
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var cpu = 8
+ @State private var memoryMB = 8192
+ @State private var network = "nat"
+ @State private var bridgeInterface = ""
+
+ private var currentNetwork: String {
+ machine.network.mode == "hostOnly" ? "none" : machine.network.mode
+ }
+
+ var body: some View {
+ Form {
+ Section {
+ Stepper("CPU: \(cpu) cores", value: $cpu, in: 1 ... ProcessInfo.processInfo.activeProcessorCount)
+ Stepper("Memory: \(memoryMB) MB", value: $memoryMB, in: 2048 ... 65536, step: 1024)
+ } header: {
+ Text("Hardware")
+ }
+ Section("Network") {
+ Picker("Mode", selection: $network) {
+ Text("NAT").tag("nat")
+ Text("Bridged").tag("bridged")
+ Text("None").tag("none")
+ }
+ if network == "bridged" {
+ TextField("Interface", text: $bridgeInterface, prompt: Text("First available"))
+ }
+ }
+ }
+ .formStyle(.grouped)
+ .navigationTitle("\(machine.name) Settings")
+ .frame(width: 440)
+ .fixedSize(horizontal: false, vertical: true)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { dismiss() }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Save") { save() }
+ }
+ }
+ .onAppear {
+ cpu = machine.cpuCount
+ memoryMB = machine.memoryMB
+ network = currentNetwork
+ bridgeInterface = machine.network.bridgeInterface ?? ""
+ }
+ }
+
+ private func save() {
+ let bridgeChanged = bridgeInterface != (machine.network.bridgeInterface ?? "")
+ Task {
+ await model.machines.configure(
+ machine.name,
+ cpu: cpu == machine.cpuCount ? nil : cpu,
+ memoryMB: memoryMB == machine.memoryMB ? nil : memoryMB,
+ network: network == currentNetwork && !bridgeChanged ? nil : network,
+ bridgeInterface: network == "bridged" ? bridgeInterface : nil,
+ )
+ }
+ dismiss()
+ }
+}
+
+// MARK: - Rename and clone
+
+struct VPhoneLaunchpadNameSheet: View {
+ let title: String
+ let action: String
+ let initial: String
+ var note: String?
+ let onConfirm: (String) -> Void
+ @Environment(\.dismiss) private var dismiss
+ @State private var name = ""
+
+ private var isValid: Bool {
+ VPhoneLaunchpadNames.isValidMachineName(name) && name != initial
+ }
+
+ var body: some View {
+ Form {
+ Section {
+ TextField("Name", text: $name)
+ } footer: {
+ Text(note ?? "Letters, digits, dots, dashes and underscores.")
+ .foregroundStyle(.secondary)
+ }
+ }
+ .formStyle(.grouped)
+ .navigationTitle(title)
+ .frame(width: 420)
+ .fixedSize(horizontal: false, vertical: true)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { dismiss() }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ Button(action) {
+ onConfirm(name)
+ dismiss()
+ }
+ .disabled(!isValid)
+ }
+ }
+ .onAppear { name = initial }
+ }
+}
+
+// MARK: - Export
+
+struct VPhoneLaunchpadExportView: View {
+ let name: String
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var densest = false
+ @State private var includeIPSW = false
+
+ var body: some View {
+ Form {
+ Section {
+ Toggle("Densest compression", isOn: $densest)
+ Toggle("Include the restore IPSW directory", isOn: $includeIPSW)
+ } footer: {
+ Text(densest
+ ? "Writes a .txz archive with xz -9. Smaller, and much slower."
+ : "Writes a .tzst archive with zstd -3.")
+ .foregroundStyle(.secondary)
+ }
+ }
+ .formStyle(.grouped)
+ .navigationTitle("Export \(name)")
+ .frame(width: 420)
+ .fixedSize(horizontal: false, vertical: true)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { dismiss() }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Choose Location…") { choose() }
+ }
+ }
+ }
+
+ private func choose() {
+ let panel = NSSavePanel()
+ panel.title = "Export \(name)"
+ panel.nameFieldStringValue = "\(name).\(densest ? "txz" : "tzst")"
+ guard panel.runModal() == .OK, let url = panel.url else {
+ return
+ }
+ let densest = densest
+ let includeIPSW = includeIPSW
+ Task { await model.machines.export(name, to: url, densest: densest, includeIPSW: includeIPSW) }
+ dismiss()
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
new file mode 100644
index 00000000..d4ee2da6
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift
@@ -0,0 +1,358 @@
+import AppKit
+import SwiftUI
+
+struct VPhoneLaunchpadMachinesView: View {
+ enum Sheet: Identifiable {
+ case newMachine
+ case creation(String)
+ case settings(VPhoneLaunchpadMachine)
+ case rename(String)
+ case clone(String)
+ case export(String)
+
+ var id: String {
+ switch self {
+ case .newMachine: "new"
+ case let .creation(name): "creation-\(name)"
+ case let .settings(machine): "settings-\(machine.name)"
+ case let .rename(name): "rename-\(name)"
+ case let .clone(name): "clone-\(name)"
+ case let .export(name): "export-\(name)"
+ }
+ }
+ }
+
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @State private var sheet: Sheet?
+ @State private var deletion: String?
+
+ private var library: VPhoneLaunchpadMachineLibrary {
+ model.machines
+ }
+
+ var body: some View {
+ @Bindable var library = library
+ Group {
+ if library.machines.isEmpty {
+ emptyState
+ } else {
+ VSplitView {
+ table(selection: $library.selection)
+ .frame(minHeight: 140, idealHeight: 200)
+ Group {
+ if let machine = library.selected {
+ detail(machine)
+ } else {
+ ContentUnavailableView("No Selection", systemImage: "iphone")
+ }
+ }
+ .frame(minHeight: 260)
+ }
+ }
+ }
+ .toolbar { toolbar }
+ .sheet(item: $sheet) { sheet in
+ sheetContent(sheet)
+ .environment(model)
+ }
+ .confirmationDialog(
+ "Delete \(deletion ?? "")?",
+ isPresented: Binding(get: { deletion != nil }, set: { if !$0 { deletion = nil } }),
+ ) {
+ Button("Delete", role: .destructive) {
+ if let name = deletion {
+ Task { await library.delete(name) }
+ }
+ }
+ } message: {
+ Text("The machine's disk, firmware and settings are removed. This cannot be undone.")
+ }
+ .alert(
+ library.actionError?.message ?? "",
+ isPresented: Binding(get: { library.actionError != nil }, set: { if !$0 { library.actionError = nil } }),
+ presenting: library.actionError,
+ ) { _ in
+ Button("OK") {}
+ } message: { error in
+ Text(error.detail ?? "")
+ }
+ }
+
+ // MARK: - Toolbar
+
+ @ToolbarContentBuilder
+ private var toolbar: some ToolbarContent {
+ let selected = library.selected
+ let state = selected.map { library.state(of: $0.name) }
+ ToolbarItemGroup(placement: .primaryAction) {
+ if state == .running, let selected {
+ Button {
+ Task { await library.stop(selected.name) }
+ } label: {
+ Label("Stop", systemImage: "stop.fill")
+ }
+ .help("Stop \(selected.name)")
+ } else {
+ Button {
+ if let selected {
+ library.start(selected.name)
+ }
+ } label: {
+ Label("Start", systemImage: "play.fill")
+ }
+ .help("Start the selected machine")
+ .disabled(state != .stopped)
+ }
+ Menu {
+ machineActions(selected)
+ } label: {
+ Label("Actions", systemImage: "ellipsis.circle")
+ }
+ .disabled(selected == nil)
+ Button {
+ chooseImport()
+ } label: {
+ Label("Import", systemImage: "square.and.arrow.down")
+ }
+ .help("Import an exported machine")
+ .disabled(library.globalActivity != nil)
+ Button {
+ sheet = .newMachine
+ } label: {
+ Label("New Machine", systemImage: "plus")
+ }
+ .help("Create a machine")
+ }
+ }
+
+ /// The same actions in the toolbar menu and the table's context menu.
+ @ViewBuilder
+ private func machineActions(_ machine: VPhoneLaunchpadMachine?) -> some View {
+ if let machine {
+ let isStopped = library.state(of: machine.name) == .stopped
+ Button("Start Headless") { library.start(machine.name, headless: true) }
+ .disabled(!isStopped)
+ Divider()
+ Button("Settings…") { sheet = .settings(machine) }
+ .disabled(!isStopped)
+ Button("Rename…") { sheet = .rename(machine.name) }
+ .disabled(!isStopped)
+ Button("Clone…") { sheet = .clone(machine.name) }
+ .disabled(!isStopped)
+ Button("Export…") { sheet = .export(machine.name) }
+ .disabled(!isStopped)
+ Divider()
+ Button("Show in Finder") {
+ NSWorkspace.shared.activateFileViewerSelecting([library.libraryRoot.appendingPathComponent(machine.name)])
+ }
+ Button("Show Console Log") {
+ NSWorkspace.shared.open(VPhoneLaunchpadMachineLibrary.consoleLog(machine.name))
+ }
+ Divider()
+ Button("Delete…", role: .destructive) { deletion = machine.name }
+ .disabled(!isStopped)
+ }
+ }
+
+ // MARK: - Table
+
+ private func table(selection: Binding<String?>) -> some View {
+ Table(library.machines, selection: selection) {
+ TableColumn("Name", value: \.name)
+ TableColumn("iOS") { machine in
+ Text(machine.restoreInfo.map { "\($0.ios.version) (\($0.ios.build))" } ?? "—")
+ }
+ TableColumn("State") { machine in
+ stateLabel(machine.name)
+ }
+ .width(min: 120, ideal: 180)
+ TableColumn("CPU") { machine in
+ Text("\(machine.cpuCount)").monospacedDigit()
+ }
+ .width(50)
+ TableColumn("Memory") { machine in
+ Text(Self.memory(machine.memoryMB)).monospacedDigit()
+ }
+ .width(70)
+ TableColumn("Disk") { machine in
+ Text(Self.disk(machine.diskSizeBytes)).monospacedDigit()
+ }
+ .width(70)
+ }
+ .contextMenu(forSelectionType: String.self) { names in
+ machineActions(library.machines.first { names.contains($0.name) })
+ } primaryAction: { names in
+ if let name = names.first, library.state(of: name) == .stopped {
+ library.start(name)
+ }
+ }
+ }
+
+ private func stateLabel(_ name: String) -> some View {
+ let (status, text): (VPhoneLaunchpadStatus, String) = switch library.state(of: name) {
+ case .running: (.passed, "Running")
+ case .stopped: (.pending, "Stopped")
+ case let .busy(activity): (.running, activity.prefix(1).uppercased() + activity.dropFirst())
+ }
+ return Label {
+ Text(text).lineLimit(1)
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: status)
+ }
+ }
+
+ private var emptyState: some View {
+ ContentUnavailableView {
+ Label("No Machines", systemImage: "iphone")
+ } description: {
+ Text(library.listError ?? "Machines in \(VPhoneLaunchpadHostSetup.abbreviated(library.libraryRoot)) appear here.")
+ } actions: {
+ Button("New Machine…") { sheet = .newMachine }
+ .buttonStyle(.borderedProminent)
+ Button("Import…") { chooseImport() }
+ }
+ }
+
+ // MARK: - Detail
+
+ private func detail(_ machine: VPhoneLaunchpadMachine) -> some View {
+ Form {
+ Section {
+ if let creation = library.creations[machine.name] {
+ creationSummary(creation)
+ }
+ LabeledContent("State") { stateLabel(machine.name) }
+ if let started = library.startedAt[machine.name] {
+ LabeledContent("Started", value: started.formatted(date: .omitted, time: .shortened))
+ }
+ LabeledContent("Firmware", value: machine.restoreInfo.map {
+ "iOS \($0.ios.version) (\($0.ios.build)) on cloudOS \($0.cloudOS.version)"
+ } ?? "Not restored")
+ if let variant = machine.restoreInfo?.variant {
+ LabeledContent("Variant", value: variant)
+ }
+ LabeledContent(
+ "Hardware",
+ value: "\(machine.cpuCount) cores, \(Self.memory(machine.memoryMB)), \(Self.disk(machine.diskSizeBytes)) disk",
+ )
+ LabeledContent("Network", value: machine.networkDescription)
+ if let udid = machine.udid {
+ LabeledContent("UDID") { Text(udid).textSelection(.enabled) }
+ }
+ LabeledContent(
+ "Location",
+ value: VPhoneLaunchpadHostSetup.abbreviated(library.libraryRoot.appendingPathComponent(machine.name)),
+ )
+ } header: {
+ Text(machine.name)
+ }
+
+ Section("Console") {
+ VPhoneLaunchpadLogView(lines: library.consoles[machine.name] ?? [])
+ .frame(minHeight: 160)
+ }
+
+ Section("Recent Commands") {
+ commands
+ }
+ }
+ .formStyle(.grouped)
+ .onAppear { library.loadConsoleIfNeeded(machine.name) }
+ .onChange(of: machine.name) { _, name in library.loadConsoleIfNeeded(name) }
+ }
+
+ private func creationSummary(_ creation: VPhoneLaunchpadCreationPipeline) -> some View {
+ LabeledContent {
+ Button("Show Progress") { sheet = .creation(creation.options.name) }
+ } label: {
+ if creation.isRunning {
+ Label { Text("Creating: \(creation.current?.title ?? "")") } icon: { VPhoneLaunchpadStatusIcon(status: .running) }
+ } else if creation.isFinished {
+ Label { Text("Created") } icon: { VPhoneLaunchpadStatusIcon(status: .passed) }
+ } else {
+ Label { Text(creation.failure?.message ?? "Creation stopped") } icon: { VPhoneLaunchpadStatusIcon(status: .failed) }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var commands: some View {
+ let entries = Array(model.history.entries.suffix(12).reversed())
+ if entries.isEmpty {
+ Text("Commands Launchpad runs appear here.")
+ .foregroundStyle(.secondary)
+ }
+ ForEach(entries) { entry in
+ Label {
+ Text(entry.text)
+ .font(.system(.callout, design: .monospaced))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .textSelection(.enabled)
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: entry.status.map { $0 == 0 ? .passed : .failed } ?? .running)
+ }
+ .contextMenu {
+ Button("Copy Command") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(entry.text, forType: .string)
+ }
+ }
+ }
+ }
+
+ // MARK: - Sheets
+
+ @ViewBuilder
+ private func sheetContent(_ sheet: Sheet) -> some View {
+ switch sheet {
+ case .newMachine:
+ VPhoneLaunchpadNewMachineView { name in
+ self.sheet = .creation(name)
+ }
+ case let .creation(name):
+ if let creation = library.creations[name] {
+ VPhoneLaunchpadCreationView(creation: creation)
+ }
+ case let .settings(machine):
+ VPhoneLaunchpadMachineSettingsView(machine: machine)
+ case let .rename(name):
+ VPhoneLaunchpadNameSheet(title: "Rename \(name)", action: "Rename", initial: name) { newName in
+ Task { await library.rename(name, to: newName) }
+ }
+ case let .clone(name):
+ VPhoneLaunchpadNameSheet(
+ title: "Clone \(name)",
+ action: "Clone",
+ initial: "\(name)-clone",
+ note: "The clone boots as a new device. SEP storage is copied as is, so a restored machine may need restoring again.",
+ ) { newName in
+ Task { await library.clone(name, as: newName) }
+ }
+ case let .export(name):
+ VPhoneLaunchpadExportView(name: name)
+ }
+ }
+
+ private func chooseImport() {
+ let panel = NSOpenPanel()
+ panel.title = "Import Machine"
+ panel.message = "Choose a .tzst or .txz archive made by Export."
+ panel.canChooseDirectories = false
+ panel.allowsMultipleSelection = false
+ guard panel.runModal() == .OK, let url = panel.url else {
+ return
+ }
+ Task { await library.importArchive(url) }
+ }
+
+ // MARK: - Formatting
+
+ static func memory(_ megabytes: Int) -> String {
+ megabytes % 1024 == 0 ? "\(megabytes / 1024) GB" : "\(megabytes) MB"
+ }
+
+ static func disk(_ bytes: Int64) -> String {
+ "\(bytes / 1_073_741_824) GB"
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
new file mode 100644
index 00000000..715ea93c
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift
@@ -0,0 +1,294 @@
+import AppKit
+import SwiftUI
+
+/// Name, firmware pairing from `fw catalog`, hardware and options. Create
+/// hands off to the pipeline sheet.
+struct VPhoneLaunchpadNewMachineView: View {
+ let onCreate: (String) -> Void
+ @Environment(VPhoneLaunchpadModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var name = ""
+ @State private var catalog: VPhoneLaunchpadFirmwareCatalog?
+ @State private var catalogError: String?
+ @State private var pairing: String?
+ @State private var usesCustomSources = false
+ @State private var iphoneSource = ""
+ @State private var cloudOSSource = ""
+ @State private var cpu = 8
+ @State private var memoryMB = 8192
+ @State private var diskSizeGB = 64
+ @State private var network = "nat"
+ @State private var enableFrida = false
+ @State private var forceMaxSlide = false
+ @State private var keepArtifacts = false
+
+ private var selectedPairing: VPhoneLaunchpadFirmwareCatalog.Pairing? {
+ catalog?.pairings.first { $0.id == pairing }
+ }
+
+ private var sources: (String, String)? {
+ if usesCustomSources {
+ let iphone = iphoneSource.trimmingCharacters(in: .whitespaces)
+ let cloudOS = cloudOSSource.trimmingCharacters(in: .whitespaces)
+ return iphone.isEmpty || cloudOS.isEmpty ? nil : (iphone, cloudOS)
+ }
+ return selectedPairing.map { ($0.ios.url, $0.recommendedCloudOS.url) }
+ }
+
+ private var nameProblem: String? {
+ if name.isEmpty {
+ return nil
+ }
+ if !VPhoneLaunchpadNames.isValidMachineName(name) {
+ return "Use letters, digits, dots, dashes and underscores."
+ }
+ if model.machines.machines.contains(where: { $0.name == name }) {
+ return "A machine with this name already exists."
+ }
+ return nil
+ }
+
+ private var canCreate: Bool {
+ !name.isEmpty && nameProblem == nil && sources != nil
+ }
+
+ var body: some View {
+ Form {
+ Section {
+ TextField("Name", text: $name, prompt: Text("research-01"))
+ } footer: {
+ if let nameProblem {
+ Text(nameProblem).foregroundStyle(.red)
+ }
+ }
+
+ firmware
+
+ Section("Hardware") {
+ Stepper("CPU: \(cpu) cores", value: $cpu, in: 1 ... ProcessInfo.processInfo.activeProcessorCount)
+ Stepper("Memory: \(memoryMB) MB", value: $memoryMB, in: 2048 ... 65536, step: 1024)
+ Stepper("Disk: \(diskSizeGB) GB", value: $diskSizeGB, in: 32 ... 512, step: 16)
+ Picker("Network", selection: $network) {
+ Text("NAT").tag("nat")
+ Text("Bridged").tag("bridged")
+ Text("None").tag("none")
+ }
+ }
+
+ Section {
+ Toggle("Frida Stalker kernel relaxations", isOn: $enableFrida)
+ Toggle("Zero the dyld cache maxSlide", isOn: $forceMaxSlide)
+ Toggle("Keep the prepared restore tree", isOn: $keepArtifacts)
+ } header: {
+ Text("Options")
+ } footer: {
+ Text(spaceNote).foregroundStyle(.secondary)
+ }
+ }
+ .formStyle(.grouped)
+ .navigationTitle("New Machine")
+ .frame(width: 560, height: 620)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { dismiss() }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Create") { create() }
+ .disabled(!canCreate)
+ }
+ }
+ .task { await loadCatalog() }
+ }
+
+ // MARK: - Firmware
+
+ private var firmware: some View {
+ Section {
+ Picker("Source", selection: $usesCustomSources) {
+ Text("Catalog").tag(false)
+ Text("Custom IPSWs").tag(true)
+ }
+ .pickerStyle(.segmented)
+
+ if usesCustomSources {
+ sourceField("iPhone IPSW", $iphoneSource)
+ sourceField("cloudOS IPSW", $cloudOSSource)
+ } else if let catalog {
+ Picker("iOS", selection: $pairing) {
+ ForEach(catalog.pairings.reversed()) { pairing in
+ Text("\(pairing.ios.name) (\(pairing.build))").tag(Optional(pairing.id))
+ }
+ }
+ LabeledContent("cloudOS", value: selectedPairing?.recommendedCloudOS.name ?? "—")
+ } else if let catalogError {
+ Label(catalogError, systemImage: "exclamationmark.triangle")
+ .foregroundStyle(.secondary)
+ } else {
+ HStack {
+ ProgressView().controlSize(.small)
+ Text("Loading fw catalog…").foregroundStyle(.secondary)
+ }
+ }
+ } header: {
+ Text("Firmware")
+ } footer: {
+ if !usesCustomSources, let catalog {
+ Text("Recommended pairings for \(catalog.device) from vphone-cli fw catalog.")
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ private func sourceField(_ title: String, _ text: Binding<String>) -> some View {
+ LabeledContent(title) {
+ HStack {
+ TextField(title, text: text, prompt: Text("URL or path"))
+ .labelsHidden()
+ Button("Choose…") {
+ let panel = NSOpenPanel()
+ panel.canChooseDirectories = false
+ if panel.runModal() == .OK, let url = panel.url {
+ text.wrappedValue = url.path
+ }
+ }
+ }
+ }
+ }
+
+ /// Disk plus roughly 20 GB of IPSWs and the prepared restore tree.
+ private var spaceNote: String {
+ let root = VPhoneLaunchpadHostSetup.existingAncestor(of: model.libraryRoot)
+ let free = (try? root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))?
+ .volumeAvailableCapacityForImportantUsage ?? 0
+ return "Needs about \(diskSizeGB + 20) GB; \(free / 1_000_000_000) GB free."
+ }
+
+ // MARK: - Actions
+
+ private func loadCatalog() async {
+ guard catalog == nil, let commandLine = model.bundles.commandLine() else {
+ return
+ }
+ do {
+ let result = try await commandLine.run(["fw", "catalog", "--json"], recordInHistory: false)
+ guard result.succeeded, let data = result.jsonData else {
+ catalogError = result.tail
+ return
+ }
+ let catalog = try JSONDecoder().decode(VPhoneLaunchpadFirmwareCatalog.self, from: data)
+ self.catalog = catalog
+ pairing = catalog.pairings.last?.id
+ } catch {
+ catalogError = error.localizedDescription
+ }
+ }
+
+ private func create() {
+ guard let (iphone, cloudOS) = sources else {
+ return
+ }
+ let options = VPhoneLaunchpadCreationPipeline.Options(
+ name: name,
+ iphoneSource: iphone,
+ cloudOSSource: cloudOS,
+ cpuCount: cpu,
+ memoryMB: memoryMB,
+ diskSizeGB: diskSizeGB,
+ network: network,
+ enableFrida: enableFrida,
+ forceDyldSharedCacheMaxSlide: forceMaxSlide,
+ keepArtifacts: keepArtifacts,
+ )
+ _ = model.machines.create(options)
+ model.machines.selection = name
+ onCreate(name)
+ }
+}
+
+// MARK: - Pipeline
+
+/// The pipeline, which keeps running when this sheet closes.
+struct VPhoneLaunchpadCreationView: View {
+ let creation: VPhoneLaunchpadCreationPipeline
+ @Environment(\.dismiss) private var dismiss
+
+ var body: some View {
+ Form {
+ Section {
+ ForEach(VPhoneLaunchpadCreationPipeline.Step.allCases) { step in
+ stepRow(step)
+ }
+ } footer: {
+ if let failure = creation.failure {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(failure.message).foregroundStyle(.red)
+ if let detail = failure.detail {
+ Text(detail)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ .lineLimit(8)
+ }
+ }
+ } else if creation.isRunning {
+ Text("Closing this window keeps it running.").foregroundStyle(.secondary)
+ }
+ }
+ Section("Log") {
+ VPhoneLaunchpadLogView(lines: creation.log)
+ .frame(minHeight: 200)
+ }
+ }
+ .formStyle(.grouped)
+ .navigationTitle("Creating \(creation.options.name)")
+ .frame(width: 720, height: 640)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Close") { dismiss() }
+ }
+ ToolbarItem(placement: .destructiveAction) {
+ if creation.isRunning {
+ Button("Stop Creating", role: .destructive) { creation.cancel() }
+ }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ if !creation.isRunning, let step = creation.failedStep {
+ Button("Retry from \(step.title)") { creation.start(from: step) }
+ }
+ }
+ }
+ }
+
+ private func stepRow(_ step: VPhoneLaunchpadCreationPipeline.Step) -> some View {
+ LabeledContent {
+ Text(creation.durations[step].map(Self.duration) ?? "")
+ .monospacedDigit()
+ .foregroundStyle(.secondary)
+ } label: {
+ Label {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 4) {
+ Text(step.title)
+ if step.needsRoot {
+ Image(systemName: "lock.fill")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .help("Runs as root through the privileged helper")
+ }
+ }
+ Text("vphone-cli \(creation.command(for: step))")
+ .font(.system(.caption, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ } icon: {
+ VPhoneLaunchpadStatusIcon(status: creation.status(step))
+ }
+ }
+ }
+
+ static func duration(_ interval: TimeInterval) -> String {
+ Duration.seconds(interval).formatted(.time(pattern: interval >= 3600 ? .hourMinuteSecond : .minuteSecond))
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swift
new file mode 100644
index 00000000..19fb3e51
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swift
@@ -0,0 +1,186 @@
+import CryptoKit
+import Darwin
+import Foundation
+
+/// Installs one VPhone.bundle release into the root-owned store.
+enum VPhoneLaunchpadHelperBundleInstaller {
+ static func install(version: String, archive: FileHandle, sha256: String) throws {
+ guard VPhoneLaunchpadNames.isValidVersion(version) else {
+ throw VPhoneLaunchpadHelperError("\"\(version)\" is not a valid bundle version.")
+ }
+ let expected = sha256.lowercased().replacingOccurrences(of: "sha256:", with: "")
+ guard expected.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil else {
+ throw VPhoneLaunchpadHelperError("\"\(sha256)\" is not a SHA-256 digest.")
+ }
+
+ let fileManager = FileManager.default
+ try prepareStoreRoot()
+ let staging = VPhoneLaunchpadBundleStore.root
+ .appendingPathComponent(".staging-\(UUID().uuidString)", isDirectory: true)
+ try fileManager.createDirectory(
+ at: staging,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o700],
+ )
+ defer { try? fileManager.removeItem(at: staging) }
+
+ // Copy and hash in one pass, so the bytes that were checked are the
+ // bytes that get extracted. The caller's file stays out of reach.
+ let archiveURL = staging.appendingPathComponent("VPhone.zip")
+ let actual = try copyAndHash(from: archive, to: archiveURL)
+ guard actual == expected else {
+ throw VPhoneLaunchpadHelperError("SHA-256 mismatch: expected \(expected), got \(actual).")
+ }
+
+ let extracted = staging.appendingPathComponent("extracted", isDirectory: true)
+ try runTool("/usr/bin/ditto", ["-x", "-k", "--noqtn", archiveURL.path, extracted.path])
+ let bundle = extracted.appendingPathComponent("VPhone.bundle", isDirectory: true)
+ try requireDirectory(bundle, "The archive does not contain VPhone.bundle.")
+ for name in VPhoneLaunchpadBundleStore.pinnedExecutables {
+ let executable = bundle.appendingPathComponent("Contents/MacOS/\(name)")
+ try requireRegularFile(executable, "VPhone.bundle has no \(name).")
+ }
+
+ try VPhoneLaunchpadHelperCodeCheck.requireValidBundle(bundle)
+ var cdhashes: [String: String] = [:]
+ for name in VPhoneLaunchpadBundleStore.pinnedExecutables {
+ cdhashes[name] = try VPhoneLaunchpadHelperCodeCheck.cdhash(
+ of: bundle.appendingPathComponent("Contents/MacOS/\(name)"),
+ )
+ }
+ try makeRootOwned(bundle)
+
+ let destination = VPhoneLaunchpadBundleStore.directory(version: version)
+ if fileManager.fileExists(atPath: destination.path) {
+ try fileManager.removeItem(at: destination)
+ }
+ try fileManager.createDirectory(
+ at: destination,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o755],
+ )
+ try fileManager.moveItem(at: bundle, to: VPhoneLaunchpadBundleStore.bundle(version: version))
+
+ let receipt = VPhoneLaunchpadBundleReceipt(
+ version: version,
+ sha256: actual,
+ installedAt: Date(),
+ cdhashes: cdhashes,
+ )
+ let receiptURL = VPhoneLaunchpadBundleStore.receipt(version: version)
+ try VPhoneLaunchpadBundleReceipt.encoder.encode(receipt).write(to: receiptURL, options: .atomic)
+ chmod(receiptURL.path, 0o644)
+ }
+
+ static func remove(version: String) throws {
+ guard VPhoneLaunchpadNames.isValidVersion(version) else {
+ throw VPhoneLaunchpadHelperError("\"\(version)\" is not a valid bundle version.")
+ }
+ let directory = VPhoneLaunchpadBundleStore.directory(version: version)
+ guard FileManager.default.fileExists(atPath: directory.path) else {
+ return
+ }
+ try FileManager.default.removeItem(at: directory)
+ }
+
+ // MARK: - Store root
+
+ /// Creates the store and refuses to use one that anyone but root could
+ /// have prepared, since the helper later executes from it.
+ private static func prepareStoreRoot() throws {
+ let parent = VPhoneLaunchpadBundleStore.root.deletingLastPathComponent()
+ for directory in [parent, VPhoneLaunchpadBundleStore.root] {
+ if !FileManager.default.fileExists(atPath: directory.path) {
+ try FileManager.default.createDirectory(
+ at: directory,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o755, .ownerAccountID: 0, .groupOwnerAccountID: 0],
+ )
+ }
+ var info = stat()
+ guard lstat(directory.path, &info) == 0,
+ (info.st_mode & S_IFMT) == S_IFDIR,
+ info.st_uid == 0,
+ info.st_mode & 0o022 == 0
+ else {
+ throw VPhoneLaunchpadHelperError(
+ "\(directory.path) must be a directory owned by root and not writable by others.",
+ )
+ }
+ }
+ }
+
+ // MARK: - File helpers
+
+ private static func copyAndHash(from source: FileHandle, to destination: URL) throws -> String {
+ guard FileManager.default.createFile(
+ atPath: destination.path,
+ contents: nil,
+ attributes: [.posixPermissions: 0o600],
+ ) else {
+ throw VPhoneLaunchpadHelperError("Cannot create \(destination.path).")
+ }
+ let output = try FileHandle(forWritingTo: destination)
+ defer { try? output.close() }
+ var hasher = SHA256()
+ try source.seek(toOffset: 0)
+ while let chunk = try source.read(upToCount: 1 << 20), !chunk.isEmpty {
+ hasher.update(data: chunk)
+ try output.write(contentsOf: chunk)
+ }
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// root:wheel and no group or other write bit anywhere in the tree.
+ /// lchown and a symlink check keep this from following links out.
+ private static func makeRootOwned(_ root: URL) throws {
+ var paths = [root.path]
+ if let enumerator = FileManager.default.enumerator(atPath: root.path) {
+ for case let relative as String in enumerator {
+ paths.append(root.appendingPathComponent(relative).path)
+ }
+ }
+ for path in paths {
+ var info = stat()
+ guard lstat(path, &info) == 0 else {
+ throw VPhoneLaunchpadHelperError("Cannot inspect \(path).")
+ }
+ guard lchown(path, 0, 0) == 0 else {
+ throw VPhoneLaunchpadHelperError("Cannot change the owner of \(path).")
+ }
+ if (info.st_mode & S_IFMT) != S_IFLNK {
+ chmod(path, info.st_mode & 0o7755)
+ }
+ }
+ }
+
+ private static func requireDirectory(_ url: URL, _ message: String) throws {
+ var info = stat()
+ guard lstat(url.path, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR else {
+ throw VPhoneLaunchpadHelperError(message)
+ }
+ }
+
+ private static func requireRegularFile(_ url: URL, _ message: String) throws {
+ var info = stat()
+ guard lstat(url.path, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG else {
+ throw VPhoneLaunchpadHelperError(message)
+ }
+ }
+
+ private static func runTool(_ path: String, _ arguments: [String]) throws {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: path)
+ process.arguments = arguments
+ process.standardInput = FileHandle.nullDevice
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ process.waitUntilExit()
+ guard process.terminationStatus == 0 else {
+ throw VPhoneLaunchpadHelperError(
+ "\(URL(fileURLWithPath: path).lastPathComponent) exited with status \(process.terminationStatus).",
+ )
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperCodeCheck.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperCodeCheck.swift
new file mode 100644
index 00000000..0f729cb5
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperCodeCheck.swift
@@ -0,0 +1,72 @@
+import Foundation
+import Security
+
+// MARK: - Error
+
+struct VPhoneLaunchpadHelperError: LocalizedError {
+ let message: String
+
+ init(_ message: String) {
+ self.message = message
+ }
+
+ var errorDescription: String? {
+ message
+ }
+}
+
+// MARK: - Code signature checks
+
+enum VPhoneLaunchpadHelperCodeCheck {
+ /// Strict validation of a bundle and everything nested in it. The release
+ /// bundle is ad hoc signed, so this proves integrity, not origin; origin
+ /// comes from the archive's SHA-256.
+ static func requireValidBundle(_ url: URL) throws {
+ let code = try staticCode(url)
+ let flags = SecCSFlags(
+ rawValue: kSecCSCheckAllArchitectures | kSecCSStrictValidate | kSecCSCheckNestedCode,
+ )
+ var error: Unmanaged<CFError>?
+ let status = SecStaticCodeCheckValidityWithErrors(code, flags, nil, &error)
+ guard status == errSecSuccess else {
+ let reason = error.map { "\($0.takeRetainedValue())" } ?? "OSStatus \(status)"
+ throw VPhoneLaunchpadHelperError("VPhone.bundle failed signature validation: \(reason)")
+ }
+ }
+
+ /// Hex cdhash of one Mach-O.
+ static func cdhash(of url: URL) throws -> String {
+ let code = try staticCode(url)
+ var information: CFDictionary?
+ let status = SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &information)
+ guard status == errSecSuccess,
+ let dictionary = information as? [String: Any],
+ let hash = dictionary[kSecCodeInfoUnique as String] as? Data
+ else {
+ throw VPhoneLaunchpadHelperError("\(url.lastPathComponent) has no readable code signature.")
+ }
+ return hash.map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// Refuses to go on unless `url` still has the cdhash recorded at install.
+ static func requireCDHash(_ url: URL, _ expected: String?) throws {
+ guard let expected else {
+ throw VPhoneLaunchpadHelperError("The bundle receipt has no cdhash for \(url.lastPathComponent).")
+ }
+ let actual = try cdhash(of: url)
+ guard actual == expected else {
+ throw VPhoneLaunchpadHelperError(
+ "\(url.lastPathComponent) changed since it was installed (cdhash \(actual), expected \(expected)).",
+ )
+ }
+ }
+
+ private static func staticCode(_ url: URL) throws -> SecStaticCode {
+ var code: SecStaticCode?
+ let status = SecStaticCodeCreateWithPath(url as CFURL, [], &code)
+ guard status == errSecSuccess, let code else {
+ throw VPhoneLaunchpadHelperError("Cannot read the code signature of \(url.path) (OSStatus \(status)).")
+ }
+ return code
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift
new file mode 100644
index 00000000..ae032dec
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift
@@ -0,0 +1,90 @@
+import Darwin
+import Foundation
+
+/// A validated `vphone-cli cfw install` invocation. Built only from a store
+/// bundle whose cdhash still matches its receipt, and only for a VM directory
+/// the calling user owns.
+struct VPhoneLaunchpadHelperFirmwareRequest {
+ let executable: URL
+ let arguments: [String]
+ let environment: [String: String]
+ let workingDirectory: URL
+
+ init(
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ forceDyldSharedCacheMaxSlide: Bool,
+ keepArtifacts: Bool,
+ callerUID: uid_t,
+ callerGID: gid_t,
+ ) throws {
+ guard VPhoneLaunchpadNames.isValidVersion(bundleVersion) else {
+ throw VPhoneLaunchpadHelperError("\"\(bundleVersion)\" is not a valid bundle version.")
+ }
+ guard let receipt = VPhoneLaunchpadBundleReceipt.load(version: bundleVersion) else {
+ throw VPhoneLaunchpadHelperError("VPhone.bundle \(bundleVersion) is not installed.")
+ }
+ let executable = VPhoneLaunchpadBundleStore.executable(version: bundleVersion, named: "vphone-cli")
+ try VPhoneLaunchpadHelperCodeCheck.requireCDHash(executable, receipt.cdhashes["vphone-cli"])
+
+ guard VPhoneLaunchpadNames.isValidMachineName(machineName) else {
+ throw VPhoneLaunchpadHelperError("\"\(machineName)\" is not a valid machine name.")
+ }
+ // The path must already be canonical: no symlink anywhere in it, so a
+ // component cannot be swapped to point root somewhere else.
+ guard libraryRoot.hasPrefix("/"), let resolved = realpath(libraryRoot, nil) else {
+ throw VPhoneLaunchpadHelperError("The library root \(libraryRoot) does not exist.")
+ }
+ let canonical = String(cString: resolved)
+ free(resolved)
+ guard canonical == libraryRoot else {
+ throw VPhoneLaunchpadHelperError("The library root must be a canonical path without symlinks.")
+ }
+ let machine = URL(fileURLWithPath: libraryRoot, isDirectory: true)
+ .appendingPathComponent(machineName, isDirectory: true)
+ try Self.requireDirectory(libraryRoot, ownedBy: callerUID)
+ try Self.requireDirectory(machine.path, ownedBy: callerUID)
+
+ guard let account = getpwuid(callerUID) else {
+ throw VPhoneLaunchpadHelperError("Unknown user \(callerUID).")
+ }
+ let userName = String(cString: account.pointee.pw_name)
+ let home = String(cString: account.pointee.pw_dir)
+
+ var arguments = ["cfw", "install", machineName, "--library-root", libraryRoot]
+ if forceDyldSharedCacheMaxSlide {
+ arguments.append("--force-dsc-maxslide")
+ }
+ if keepArtifacts {
+ arguments.append("--keep-artifacts")
+ }
+
+ self.executable = executable
+ self.arguments = arguments
+ workingDirectory = machine
+ // The same environment `sudo vphone-cli cfw install` sees: SUDO_UID
+ // and SUDO_GID are how the installer hands root-created files back
+ // to the user afterwards.
+ environment = [
+ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",
+ "HOME": home,
+ "USER": userName,
+ "LOGNAME": userName,
+ "SUDO_USER": userName,
+ "SUDO_UID": String(callerUID),
+ "SUDO_GID": String(callerGID),
+ "LANG": "en_US.UTF-8",
+ ]
+ }
+
+ private static func requireDirectory(_ path: String, ownedBy uid: uid_t) throws {
+ var info = stat()
+ guard lstat(path, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR else {
+ throw VPhoneLaunchpadHelperError("\(path) is not a directory.")
+ }
+ guard info.st_uid == uid else {
+ throw VPhoneLaunchpadHelperError("\(path) is not owned by the requesting user.")
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperListenerDelegate.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperListenerDelegate.swift
new file mode 100644
index 00000000..40264851
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperListenerDelegate.swift
@@ -0,0 +1,25 @@
+import Foundation
+
+/// Accepts only connections from a process that satisfies the same
+/// requirement SMJobBless used to authorize the installer: the app's
+/// identifier, signed by the same team.
+final class VPhoneLaunchpadHelperListenerDelegate: NSObject, NSXPCListenerDelegate {
+ func listener(_: NSXPCListener, shouldAcceptNewConnection connection: NSXPCConnection) -> Bool {
+ guard let requirement = Self.clientRequirement() else {
+ return false
+ }
+ connection.setCodeSigningRequirement(requirement)
+ connection.exportedInterface = NSXPCInterface(with: VPhoneLaunchpadHelperProtocol.self)
+ connection.remoteObjectInterface = NSXPCInterface(with: VPhoneLaunchpadHelperClientProtocol.self)
+ connection.exportedObject = VPhoneLaunchpadHelperService(connection: connection)
+ connection.resume()
+ return true
+ }
+
+ /// The first SMAuthorizedClients entry of the helper's embedded
+ /// Info.plist. Reusing it keeps one requirement string for both checks.
+ static func clientRequirement() -> String? {
+ let clients = Bundle.main.object(forInfoDictionaryKey: "SMAuthorizedClients") as? [String]
+ return clients?.first
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
new file mode 100644
index 00000000..46be231e
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
@@ -0,0 +1,156 @@
+import Darwin
+import Foundation
+
+/// The object exported to one app connection.
+final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtocol, @unchecked Sendable {
+ private weak var connection: NSXPCConnection?
+ private let callerUID: uid_t
+ private let callerGID: gid_t
+ private let work = DispatchQueue(label: "com.vphone.launchpad.helper.work")
+
+ /// One CFW install at a time across every connection: two installs
+ /// host-mounting disks at once is never what anyone wants.
+ private static let firmwareLock = NSLock()
+ nonisolated(unsafe) private static var firmwareProcess: Process?
+
+ init(connection: NSXPCConnection) {
+ self.connection = connection
+ callerUID = connection.effectiveUserIdentifier
+ callerGID = connection.effectiveGroupIdentifier
+ }
+
+ // MARK: - Version
+
+ func helperVersion(reply: @escaping @Sendable (String) -> Void) {
+ reply(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0")
+ }
+
+ // MARK: - Bundles
+
+ func installBundle(
+ version: String,
+ archive: FileHandle,
+ sha256: String,
+ reply: @escaping @Sendable (String?) -> Void,
+ ) {
+ work.async {
+ do {
+ try VPhoneLaunchpadHelperBundleInstaller.install(version: version, archive: archive, sha256: sha256)
+ reply(nil)
+ } catch {
+ reply(error.localizedDescription)
+ }
+ }
+ }
+
+ func removeBundle(version: String, reply: @escaping @Sendable (String?) -> Void) {
+ work.async {
+ do {
+ try VPhoneLaunchpadHelperBundleInstaller.remove(version: version)
+ reply(nil)
+ } catch {
+ reply(error.localizedDescription)
+ }
+ }
+ }
+
+ // MARK: - CFW install
+
+ func installCustomFirmware(
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ forceDyldSharedCacheMaxSlide: Bool,
+ keepArtifacts: Bool,
+ reply: @escaping @Sendable (Int32, String?) -> Void,
+ ) {
+ let callerUID = callerUID
+ let callerGID = callerGID
+ DispatchQueue.global(qos: .userInitiated).async { [self] in
+ let request: VPhoneLaunchpadHelperFirmwareRequest
+ do {
+ request = try VPhoneLaunchpadHelperFirmwareRequest(
+ bundleVersion: bundleVersion,
+ machineName: machineName,
+ libraryRoot: libraryRoot,
+ forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,
+ keepArtifacts: keepArtifacts,
+ callerUID: callerUID,
+ callerGID: callerGID,
+ )
+ } catch {
+ reply(-1, error.localizedDescription)
+ return
+ }
+
+ let process = Process()
+ process.executableURL = request.executable
+ process.arguments = request.arguments
+ process.environment = request.environment
+ process.currentDirectoryURL = request.workingDirectory
+ let pipe = Pipe()
+ process.standardInput = FileHandle.nullDevice
+ process.standardOutput = pipe
+ process.standardError = pipe
+
+ Self.firmwareLock.lock()
+ guard Self.firmwareProcess == nil else {
+ Self.firmwareLock.unlock()
+ reply(-1, "Another CFW install is already running.")
+ return
+ }
+ Self.firmwareProcess = process
+ Self.firmwareLock.unlock()
+ defer {
+ Self.firmwareLock.lock()
+ Self.firmwareProcess = nil
+ Self.firmwareLock.unlock()
+ }
+
+ do {
+ try process.run()
+ } catch {
+ reply(-1, "Cannot start vphone-cli: \(error.localizedDescription)")
+ return
+ }
+ emit("$ vphone-cli \(request.arguments.joined(separator: " ")) (as root)")
+ VPhoneLaunchpadLineReader.readLines(from: pipe.fileHandleForReading) { emit($0) }
+ process.waitUntilExit()
+ reply(process.terminationStatus, nil)
+ }
+ }
+
+ func cancelCustomFirmware(reply: @escaping @Sendable () -> Void) {
+ Self.firmwareLock.lock()
+ Self.firmwareProcess?.interrupt()
+ Self.firmwareLock.unlock()
+ reply()
+ }
+
+ // MARK: - Uninstall
+
+ func uninstallHelper(reply: @escaping @Sendable (String?) -> Void) {
+ let label = VPhoneLaunchpadHelperIdentity.label
+ let fileManager = FileManager.default
+ try? fileManager.removeItem(atPath: "/Library/LaunchDaemons/\(label).plist")
+ try? fileManager.removeItem(atPath: "/Library/PrivilegedHelperTools/\(label)")
+ reply(nil)
+ // Booting out our own job ends this process; give the reply a moment
+ // to leave first.
+ DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/launchctl")
+ process.arguments = ["bootout", "system/\(label)"]
+ try? process.run()
+ process.waitUntilExit()
+ exit(0)
+ }
+ }
+
+ // MARK: - Output
+
+ private func emit(_ line: String) {
+ let client = connection?.remoteObjectProxy as? VPhoneLaunchpadHelperClientProtocol
+ client?.helperDidEmit(line: line)
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swift
new file mode 100644
index 00000000..320da8f0
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swift
@@ -0,0 +1,11 @@
+import Foundation
+
+// launchd starts this on demand for the Mach service named in the embedded
+// launchd plist, and SMJobBless has already checked that the client that
+// installed it satisfies SMAuthorizedClients. Each connection checks that again.
+
+let delegate = VPhoneLaunchpadHelperListenerDelegate()
+let listener = NSXPCListener(machServiceName: VPhoneLaunchpadHelperIdentity.machServiceName)
+listener.delegate = delegate
+listener.resume()
+dispatchMain()
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift
new file mode 100644
index 00000000..8fd0ab66
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift
@@ -0,0 +1,84 @@
+import Foundation
+
+// MARK: - Layout
+
+/// The root-owned store that holds installed VPhone.bundle versions. Only the
+/// helper writes here; the app and every child it starts only read. That is
+/// what lets the helper run `vphone-cli` from the store as root: nobody but
+/// root can swap the binary between verification and execution.
+nonisolated enum VPhoneLaunchpadBundleStore {
+ static let root = URL(
+ fileURLWithPath: "/Library/Application Support/vphone-launchpad/Bundles",
+ isDirectory: true,
+ )
+
+ static func directory(version: String) -> URL {
+ root.appendingPathComponent(version, isDirectory: true)
+ }
+
+ static func bundle(version: String) -> URL {
+ directory(version: version).appendingPathComponent("VPhone.bundle", isDirectory: true)
+ }
+
+ static func executable(version: String, named name: String) -> URL {
+ bundle(version: version).appendingPathComponent("Contents/MacOS/\(name)")
+ }
+
+ static func receipt(version: String) -> URL {
+ directory(version: version).appendingPathComponent("receipt.json")
+ }
+
+ /// The Mach-O files whose cdhash the receipt records at install time and
+ /// the helper checks again before running anything as root.
+ static let pinnedExecutables = ["vphone-cli", "vphone-vm"]
+}
+
+// MARK: - Receipt
+
+/// Written by the helper next to each installed bundle.
+nonisolated struct VPhoneLaunchpadBundleReceipt: Codable, Equatable, Sendable {
+ let version: String
+ let sha256: String
+ let installedAt: Date
+ /// Executable name to hex cdhash.
+ let cdhashes: [String: String]
+
+ static func load(version: String) -> VPhoneLaunchpadBundleReceipt? {
+ guard let data = try? Data(contentsOf: VPhoneLaunchpadBundleStore.receipt(version: version)) else {
+ return nil
+ }
+ return try? decoder.decode(Self.self, from: data)
+ }
+
+ static let decoder: JSONDecoder = {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return decoder
+ }()
+
+ static let encoder: JSONEncoder = {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ return encoder
+ }()
+}
+
+// MARK: - Argument validation
+
+/// Shapes both sides accept for names that end up in paths or argv. The app
+/// checks them to give an early message; the helper checks them because it
+/// must not trust the app.
+nonisolated enum VPhoneLaunchpadNames {
+ static func isValidVersion(_ value: String) -> Bool {
+ matches(value, "^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$") && !value.contains("..")
+ }
+
+ static func isValidMachineName(_ value: String) -> Bool {
+ matches(value, "^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$") && !value.contains("..")
+ }
+
+ private static func matches(_ value: String, _ pattern: String) -> Bool {
+ value.range(of: pattern, options: .regularExpression) != nil
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
new file mode 100644
index 00000000..c64e615b
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
@@ -0,0 +1,63 @@
+import Foundation
+
+// MARK: - Identity
+
+/// Names both sides of the privileged helper agree on. The label is also the
+/// helper's file name under /Library/PrivilegedHelperTools and the key of the
+/// app's SMPrivilegedExecutables entry.
+nonisolated enum VPhoneLaunchpadHelperIdentity {
+ static let label = "com.vphone.launchpad.helper"
+ static let machServiceName = label
+}
+
+// MARK: - Helper interface
+
+/// The whole root surface of vphone-launchpad. Every call is a fixed verb with
+/// validated arguments; there is deliberately no "run this command" entry.
+@objc(VPhoneLaunchpadHelperProtocol)
+nonisolated protocol VPhoneLaunchpadHelperProtocol {
+ /// CFBundleVersion of the running helper, compared against the copy
+ /// embedded in the app to decide whether to bless it again.
+ func helperVersion(reply: @escaping @Sendable (String) -> Void)
+
+ /// Copies the archive from `archive` into a root-owned staging directory,
+ /// checks it against `sha256`, verifies the bundle's signature, and moves
+ /// it into the root-owned bundle store. Replies with an error message, or
+ /// nil on success.
+ func installBundle(
+ version: String,
+ archive: FileHandle,
+ sha256: String,
+ reply: @escaping @Sendable (String?) -> Void,
+ )
+
+ /// Removes one version from the bundle store.
+ func removeBundle(version: String, reply: @escaping @Sendable (String?) -> Void)
+
+ /// Runs `vphone-cli cfw install` from a store bundle as root, on behalf of
+ /// the calling user. Output lines arrive through
+ /// `VPhoneLaunchpadHelperClientProtocol`. Replies with the exit status and
+ /// an error message when the request was refused before running.
+ func installCustomFirmware(
+ bundleVersion: String,
+ machineName: String,
+ libraryRoot: String,
+ forceDyldSharedCacheMaxSlide: Bool,
+ keepArtifacts: Bool,
+ reply: @escaping @Sendable (Int32, String?) -> Void,
+ )
+
+ /// Sends SIGINT to a running CFW install.
+ func cancelCustomFirmware(reply: @escaping @Sendable () -> Void)
+
+ /// Removes the helper's launchd job and binary, then exits.
+ func uninstallHelper(reply: @escaping @Sendable (String?) -> Void)
+}
+
+// MARK: - Client interface
+
+/// Exported by the app so the helper can stream command output back.
+@objc(VPhoneLaunchpadHelperClientProtocol)
+nonisolated protocol VPhoneLaunchpadHelperClientProtocol {
+ func helperDidEmit(line: String)
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift
new file mode 100644
index 00000000..6710a0de
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift
@@ -0,0 +1,44 @@
+import Foundation
+
+/// Splits a child's output into display lines. `vphone-cli` redraws progress
+/// with carriage returns and colours some output, so both `\r` and `\n` end a
+/// line, ANSI escape sequences are dropped, and blank lines are skipped.
+nonisolated struct VPhoneLaunchpadLineSplitter {
+ private var buffer = Data()
+
+ mutating func feed(_ data: Data, _ onLine: (String) -> Void) {
+ buffer.append(data)
+ while let end = buffer.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {
+ Self.emit(buffer[buffer.startIndex ..< end], onLine)
+ buffer.removeSubrange(buffer.startIndex ... end)
+ }
+ }
+
+ mutating func flush(_ onLine: (String) -> Void) {
+ Self.emit(buffer, onLine)
+ buffer.removeAll()
+ }
+
+ private static func emit(_ bytes: Data, _ onLine: (String) -> Void) {
+ let text = String(decoding: bytes, as: UTF8.self)
+ .replacingOccurrences(of: "\u{1B}\\[[0-9;?]*[ -/]*[@-~]", with: "", options: .regularExpression)
+ if !text.trimmingCharacters(in: .whitespaces).isEmpty {
+ onLine(text)
+ }
+ }
+}
+
+nonisolated enum VPhoneLaunchpadLineReader {
+ /// Reads `handle` until end of file on the calling thread.
+ static func readLines(from handle: FileHandle, onLine: (String) -> Void) {
+ var splitter = VPhoneLaunchpadLineSplitter()
+ while true {
+ let chunk = handle.availableData
+ if chunk.isEmpty {
+ break
+ }
+ splitter.feed(chunk, onLine)
+ }
+ splitter.flush(onLine)
+ }
+}