Run a virtual iPhone on an Apple Silicon Mac.
Swift
Set the UDID misagent sees from the VM's Device menu
Lakr2aaafaf2ad64
diff --git a/Research/Guest/xcode_install_signature_gate.md b/Research/Guest/xcode_install_signature_gate.mdindex a519d257..b82467e6 100644--- a/Research/Guest/xcode_install_signature_gate.md+++ b/Research/Guest/xcode_install_signature_gate.md@@ -265,6 +265,10 @@ the one a running guest can be reconfigured through; the `/usr/lib` copy iswhat `cfw install` ships, and it is only written when the guest has none, sore-running the installer never puts an empty file over a UDID someone set.+The VM window sets it from Device › Set UDID… and Reset UDID, through+vphoned's `udid.set` and `udid.clear` (`Research/vphoned_http_api.md`). vphoned+writes the data-volume file, reads it back and restarts misagent.+### The inconsistency this createsThe guest now answers two ways about which device it is. Xcode, `devicectl`diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 023cb945..dd0eaf66 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -286,6 +286,7 @@ request carries `"force": true`.| Packages (read-only) | `packages.list`, `status`, `info {path}`, `compare`, `tweaks`, `repos` || Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) || Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) |+| Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID libmisfix gives misagent's profile check (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids` (see below) |`processes.list` joins icli's kernel process list with `proc_pid_rusage`footprint, resident size and CPU time (`VPhoneDaemon/Native/vphoned_process.m`),@@ -294,7 +295,7 @@ Account passwords, boot logo rendering and package installation, removal andrepository changes are deliberately not exposed. `/v1/health` lists the newareas in `capabilities` (`device_info`, `display`, `audio`, `input_gestures`,`ui_inspection`, `processes`, `services`, `logs`, `network_capture`,-`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`) so a host can hide+`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`, `udid_override`) so a host can hidepanels an older agent cannot serve. icli failures reach the caller withicli's own error `code` (`failed`, `unavailable`, `device_locked`, …) andmessage.@@ -317,6 +318,20 @@ camera client loads the new hook. The result lists `installed`,`restarted_pids` and `reboot_required`, which is true when the launchd hookchanged: launchd keeps the copy it mapped at boot.+The profile UDID methods drive `libmisfix.dylib`'s `MGCopyAnswer` interpose+in misagent (`Research/Guest/xcode_install_signature_gate.md`). The hook reads+`UniqueDeviceID` from the first of `/var/db/vphone/misfix.plist` and+`/usr/lib/libmisfix.plist` that exists. vphoned owns the first: `udid.set`+stores the string exactly as sent, with no format check, so the API and+`vphone.sock`'s `rpc` verb can try unusual values; `udid.clear` removes the key+but keeps the file, so a value in the `/usr/lib` copy cannot take over. The file+is written as a binary plist in one rename and read back, then vphoned sends+SIGTERM to misagent; launchd starts it again for the next profile check. The+guest does not restart, and installd is left running so an install in progress+is not aborted. The VM window's Device › Set UDID… is stricter than the API: it+accepts only 8 and 16 hex digits joined by a hyphen (sent upper-case) or 40 hex+digits (sent lower-case).+`location.set` is IcliKit's `simulateLocation`: it sends locationd's`CLSimulationManager` the sequence Xcode uses (`stopLocationSimulation`,`clearSimulatedLocations`, `appendSimulatedLocation:`, `flush`,diff --git a/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift b/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swiftnew file mode 100644index 00000000..40a714f4--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift@@ -0,0 +1,97 @@+import Darwin+import Foundation++// MARK: - Profile UDID++/// The UDID libmisfix gives misagent when it checks a provisioning profile's+/// `ProvisionedDevices` (`VPhoneGuestComponents/MISFix`). Lockdown, Xcode and+/// devicectl keep seeing the guest's own UDID; only the hooked daemon sees+/// this one.+///+/// The hook reads the first of two files that exists and re-reads it when its+/// modification time or size changes. vphoned owns the data-volume file.+/// Clearing keeps that file with the key removed rather than deleting it:+/// the file then still comes first, so a UDID left in the `/usr/lib` copy+/// cannot take over again.+///+/// A change also stops misagent, so the next profile check runs in a fresh+/// process that has cached nothing. launchd starts misagent on demand.+/// installd is left alone: it asks misagent, and stopping it would abort an+/// install in progress.+extension GuestAPI {+ /// Must match `kConfigPaths` in `MISFixConfig.c`, in the same order.+ static let udidConfigPaths = ["/var/db/vphone/misfix.plist", "/usr/lib/libmisfix.plist"]+ static let udidConfigKey = "UniqueDeviceID"++ static func executeDeviceIdentity(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {+ switch method {+ case "udid.get":+ udidState()+ case "udid.set":+ // Stored exactly as sent, with no format check: the API is also+ // for probing what misagent does with an unusual value. The VM+ // window's menu is what holds a person to a real UDID's shape.+ try applyUDID(string(params, "udid"))+ case "udid.clear":+ try applyUDID(nil)+ default:+ nil+ }+ }++ /// Writes the setting, reads it back the way the hook resolves it, and+ /// restarts misagent.+ private static func applyUDID(_ udid: String?) throws -> [String: Any] {+ try writeUDIDConfiguration(udid)+ var state = udidState()+ guard state["path"] as? String == udidConfigPaths[0], state["udid"] as? String == udid else {+ throw GuestAPIError.operationFailed("\(udidConfigPaths[0]) did not read back as written")+ }+ state["restarted_pids"] = stopProcesses(named: "misagent")+ return state+ }++ /// The UDID the hook answers with and the file it comes from, resolved the+ /// way `MISFixCopyConfiguredDeviceIdentifier` resolves it. `udid` is null+ /// when the guest answers with its own.+ private static func udidState() -> [String: Any] {+ guard let path = udidConfigPaths.first(where: { access($0, F_OK) == 0 }) else {+ return ["udid": NSNull(), "path": NSNull()]+ }+ let udid = (readUDIDConfiguration(path)?[udidConfigKey] as? String).flatMap { $0.isEmpty ? nil : $0 }+ return ["udid": udid ?? NSNull(), "path": path]+ }++ private static func readUDIDConfiguration(_ path: String) -> [String: Any]? {+ guard let data = FileManager.default.contents(atPath: path) else { return nil }+ return try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ }++ /// Replaces the data-volume file in one rename, which is what the hook's+ /// mtime check expects. Other keys in the file are kept.+ private static func writeUDIDConfiguration(_ udid: String?) throws {+ guard let path = udidConfigPaths.first else { return }+ let directory = (path as NSString).deletingLastPathComponent+ do {+ try FileManager.default.createDirectory(+ atPath: directory,+ withIntermediateDirectories: true,+ attributes: [.posixPermissions: 0o755],+ )+ } catch {+ throw GuestAPIError.operationFailed("Could not create \(directory): \(error.localizedDescription)")+ }+ var configuration = readUDIDConfiguration(path) ?? [:]+ configuration[udidConfigKey] = udid+ do {+ // Binary, so any string the caller sends survives the round trip;+ // XML cannot carry every control character.+ let data = try PropertyListSerialization.data(fromPropertyList: configuration, format: .binary, options: 0)+ try data.write(to: URL(fileURLWithPath: path), options: .atomic)+ } catch {+ throw GuestAPIError.operationFailed("Could not write \(path): \(error.localizedDescription)")+ }+ // misagent and installd do not run as root; the hook only reads.+ chmod(path, 0o644)+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swiftindex 71d921c5..85852e4b 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift@@ -159,7 +159,9 @@ extension GuestAPI {}}- private static func stopProcesses(named name: String) -> [Int] {+ /// Sends SIGTERM to every process with this name; launchd starts an+ /// on-demand daemon again for its next client.+ static func stopProcesses(named name: String) -> [Int] {let rows = (try? listProcesses(filter: name))?["processes"] as? [[String: Any]] ?? []return rows.compactMap { row inguard row["name"] as? String == name, let pid = row["pid"] as? Int, kill(pid_t(pid), SIGTERM) == 0diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swiftindex 4e963a8c..8c8ac270 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift@@ -14,6 +14,7 @@ extension GuestAPI {executeAppDetail,executeFileTool,executeEnvironment,+ executeDeviceIdentity,]for area in areas {if let result = try area(method, params) {diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 7a363edc..da9f205c 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -93,6 +93,7 @@ enum GuestAPI {"files_app_drop","packages","environment_update",+ "udid_override",],]}diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstringsindex 64d3583f..1bf4fb65 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings@@ -2305,6 +2305,108 @@}}},+ "App installs check provisioning profiles against this UDID. Enter the UDID of a device already registered with your team. Xcode and devicectl still show the guest's own UDID." : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App installs check provisioning profiles against this UDID. Enter the UDID of a device already registered with your team. Xcode and devicectl still show the guest's own UDID."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "アプリのインストール時、プロビジョニングプロファイルはこの UDID と照合されます。チームに登録済みのデバイスの UDID を入力してください。Xcode と devicectl には引き続きゲスト自身の UDID が表示されます。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "앱을 설치할 때 프로비저닝 프로파일을 이 UDID와 대조합니다. 팀에 이미 등록된 기기의 UDID를 입력하세요. Xcode와 devicectl에는 계속 게스트 자체의 UDID가 표시됩니다."+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Khi cài ứng dụng, hồ sơ cấp phép được đối chiếu với UDID này. Hãy nhập UDID của một thiết bị đã đăng ký với nhóm của bạn. Xcode và devicectl vẫn hiển thị UDID riêng của máy khách."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "安装应用时,描述文件会与此 UDID 比对。请输入已在你的团队中注册的设备的 UDID。Xcode 和 devicectl 仍显示客体自身的 UDID。"+ }+ }+ }+ },+ "App installs now check provisioning profiles against %@." : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App installs now check provisioning profiles against %@."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "アプリのインストール時、プロビジョニングプロファイルは %@ と照合されるようになりました。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "이제 앱을 설치할 때 프로비저닝 프로파일을 %@와(과) 대조합니다."+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Từ giờ, khi cài ứng dụng, hồ sơ cấp phép được đối chiếu với %@."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "现在安装应用时,描述文件会与 %@ 比对。"+ }+ }+ }+ },+ "App installs now check provisioning profiles against the guest's own UDID." : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App installs now check provisioning profiles against the guest's own UDID."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "アプリのインストール時、プロビジョニングプロファイルはゲスト自身の UDID と照合されるようになりました。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "이제 앱을 설치할 때 프로비저닝 프로파일을 게스트 자체의 UDID와 대조합니다."+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Từ giờ, khi cài ứng dụng, hồ sơ cấp phép được đối chiếu với UDID riêng của máy khách."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "现在安装应用时,描述文件会与客体自身的 UDID 比对。"+ }+ }+ }+ },"Apple Park (Cupertino)" : {"localizations" : {"en" : {@@ -3873,6 +3975,40 @@}}},+ "Check that the guest agent is connected, then try again." : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Check that the guest agent is connected, then try again."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ゲストエージェントの接続を確認して再試行してください。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "게스트 에이전트 연결을 확인한 후 다시 시도하세요."+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Hãy kiểm tra kết nối của tác nhân máy khách rồi thử lại."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请检查客体代理连接后重试。"+ }+ }+ }+ },"Check the connection, then try again." : {"localizations" : {"ja" : {@@ -8341,6 +8477,40 @@}}},+ "Enter 8 and 16 hexadecimal digits joined by a hyphen, or 40 hexadecimal digits." : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enter 8 and 16 hexadecimal digits joined by a hyphen, or 40 hexadecimal digits."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "8 桁と 16 桁の 16 進数をハイフンでつないだもの、または 40 桁の 16 進数を入力してください。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "16진수 8자리와 16자리를 하이픈으로 연결하거나 16진수 40자리를 입력하세요."+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Hãy nhập 8 và 16 chữ số thập lục phân nối bằng dấu gạch ngang, hoặc 40 chữ số thập lục phân."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请输入用连字符连接的 8 位和 16 位十六进制数,或 40 位十六进制数。"+ }+ }+ }+ },"Enter a URL to open on the guest." : {"localizations" : {"en" : {@@ -11479,6 +11649,40 @@}}},+ "Invalid UDID" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Invalid UDID"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID が無効です"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "유효하지 않은 UDID"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID không hợp lệ"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID 无效"+ }+ }+ }+ },"Item Type" : {"localizations" : {"en" : {@@ -18224,6 +18428,40 @@}}},+ "Reset UDID" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reset UDID"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID をリセット"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID 재설정"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Đặt lại UDID"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重置 UDID"+ }+ }+ }+ },"Resident" : {"localizations" : {"ja" : {@@ -20790,6 +21028,74 @@}}},+ "Set UDID" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Set UDID"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID を設定"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID 설정"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Đặt UDID"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设置 UDID"+ }+ }+ }+ },+ "Set UDID…" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Set UDID…"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID を設定…"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID 설정…"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Đặt UDID…"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设置 UDID…"+ }+ }+ }+ },"Set the guest clipboard to this text (⌘↩)" : {"localizations" : {"en" : {@@ -24230,6 +24536,40 @@}}},+ "UDID for provisioning profile checks" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID for provisioning profile checks"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "プロビジョニングプロファイルの照合に使う UDID"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "프로비저닝 프로파일 대조에 사용할 UDID"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID dùng để đối chiếu hồ sơ cấp phép"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "用于比对描述文件的 UDID"+ }+ }+ }+ },"URL" : {"localizations" : {"ja" : {@@ -24410,6 +24750,40 @@}}},+ "Unable to Reset UDID" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Unable to Reset UDID"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID をリセットできません"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID를 재설정할 수 없음"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Không thể đặt lại UDID"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法重置 UDID"+ }+ }+ }+ },"Unable to Restart Guest" : {"localizations" : {"en" : {@@ -24472,6 +24846,40 @@}}},+ "Unable to Set UDID" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Unable to Set UDID"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID を設定できません"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "UDID를 설정할 수 없음"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Không thể đặt UDID"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法设置 UDID"+ }+ }+ }+ },"Unable to add the keychain item. Try again." : {"localizations" : {"en" : {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlDeviceIdentity.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlDeviceIdentity.swiftnew file mode 100644index 00000000..887a1c3a--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlDeviceIdentity.swift@@ -0,0 +1,53 @@+import Foundation++// MARK: - Profile UDID++/// The UDID libmisfix gives misagent for provisioning profile checks. Xcode,+/// devicectl and lockdown keep seeing the guest's own UDID. vphoned writes the+/// hook's settings file, reads it back and restarts misagent, so a change+/// applies to the next app install. The guest itself does not restart.+extension VPhoneGuestControl {+ /// The configured UDID, or nil when profiles are checked against the+ /// guest's own.+ func profileUDID() async throws -> String? {+ try await udidCall("udid.get")+ }++ /// Sets the UDID, or clears it when `udid` is nil. Returns the UDID the+ /// guest reports afterwards.+ @discardableResult+ func setProfileUDID(_ udid: String?) async throws -> String? {+ if let udid {+ return try await udidCall("udid.set", params: ["udid": udid])+ }+ return try await udidCall("udid.clear")+ }++ private func udidCall(_ method: String, params: [String: Any] = [:]) async throws -> String? {+ guard guestCapabilities.contains("udid_override") else {+ throw ControlError.unsupportedCapability("udid_override")+ }+ let result = try await call(method, params: params)+ return (result["udid"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ }++ /// The UDID in the form a provisioning profile lists it, or nil when the+ /// text is not a UDID: 8 and 16 hex digits joined by a hyphen (A12 and+ /// later, listed upper-case), or 40 hex digits (earlier devices, listed+ /// lower-case). misagent compares strings, so the case is normalized.+ ///+ /// Only the menu applies this. vphoned's `udid.set` stores any non-empty+ /// string as sent, so the API and `vphone.sock` can probe unusual values.+ nonisolated static func normalizedUDID(_ value: String) -> String? {+ let text = value.trimmingCharacters(in: .whitespacesAndNewlines)+ let isHex = { (part: Substring) in part.allSatisfy { $0.isASCII && $0.isHexDigit } }+ let parts = text.split(separator: "-", omittingEmptySubsequences: false)+ if parts.count == 2, parts[0].count == 8, parts[1].count == 16, parts.allSatisfy(isHex) {+ return text.uppercased()+ }+ if parts.count == 1, text.count == 40, isHex(Substring(text)) {+ return text.lowercased()+ }+ return nil+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swiftindex 0c71e1a7..8ae4b12e 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift@@ -34,6 +34,8 @@ class VPhoneMenuController {var settingsGetItem: NSMenuItem?var settingsSetItem: NSMenuItem?var restartGuestItem: NSMenuItem?+ var setUDIDItem: NSMenuItem?+ var resetUDIDItem: NSMenuItem?var panelMenuItems: [VPhoneGuestPanel: NSMenuItem] = [:]var rotateMenuItems: [NSMenuItem] = []var touchIDMonitor: VPhoneTouchIDMonitor? {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swiftindex ff539984..7e7dd739 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift@@ -4,7 +4,8 @@ import VPhoneCoreKit// MARK: - Device Menu-/// The phone's buttons and input, and restarting it. Sensor overrides live+/// The phone's buttons and input, the UDID it gives provisioning profile+/// checks, and restarting it. Sensor overrides live/// in the Features menu.extension VPhoneMenuController {func buildDeviceMenu() -> NSMenuItem {@@ -82,6 +83,8 @@ extension VPhoneMenuController {touchIDMenuItem = tidItemmenu.addItem(tidItem)menu.addItem(NSMenuItem.separator())+ addUDIDItems(to: menu)+ menu.addItem(NSMenuItem.separator())let restart = makeItem("Restart Guest…", action: #selector(restartGuest), symbol: "arrow.clockwise")restart.isEnabled = falserestartGuestItem = restartdiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuUDID.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuUDID.swiftnew file mode 100644index 00000000..faedf0ca--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuUDID.swift@@ -0,0 +1,117 @@+import AppKit++// MARK: - UDID Menu Items++/// The UDID the guest gives provisioning profile checks, so a team's profiles+/// for a device it already registered install here. Xcode and devicectl keep+/// showing the guest's own UDID. See `VPhoneGuestControlDeviceIdentity.swift`.+extension VPhoneMenuController {+ func addUDIDItems(to menu: NSMenu) {+ let set = makeItem("Set UDID…", action: #selector(setUDID), symbol: "person.text.rectangle")+ set.isEnabled = false+ setUDIDItem = set+ menu.addItem(set)++ let reset = makeItem("Reset UDID", action: #selector(resetUDID), symbol: "arrow.counterclockwise")+ reset.isEnabled = false+ resetUDIDItem = reset+ menu.addItem(reset)+ }++ func updateUDIDAvailability(available: Bool) {+ setUDIDItem?.isEnabled = available+ resetUDIDItem?.isEnabled = available+ }++ @objc func setUDID() {+ Task {+ let current: String?+ do {+ current = try await control.profileUDID()+ } catch {+ print("[udid] read failed: \(error)")+ current = nil+ }+ promptForUDID(initial: current ?? "")+ }+ }++ @objc func resetUDID() {+ Task {+ do {+ try await control.setProfileUDID(nil)+ VPhoneAlert.present(+ title: "Reset UDID",+ message: "App installs now check provisioning profiles against the guest's own UDID.",+ style: .informational,+ )+ } catch {+ print("[udid] reset failed: \(error)")+ VPhoneAlert.present(+ title: "Unable to Reset UDID",+ message: "Check that the guest agent is connected, then try again.",+ style: .warning,+ )+ }+ }+ }++ private func promptForUDID(initial: String) {+ let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 360, height: 24))+ field.stringValue = initial+ field.placeholderString = "00008150-000815E014B8401C"+ field.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)+ field.setAccessibilityLabel(VPhoneLocalization.text("UDID for provisioning profile checks"))++ let alert = NSAlert()+ alert.messageText = VPhoneLocalization.text("Set UDID")+ alert.informativeText = VPhoneLocalization.text(+ "App installs check provisioning profiles against this UDID. Enter the UDID of a device already registered with your team. Xcode and devicectl still show the guest's own UDID.",+ )+ alert.accessoryView = field+ alert.addButton(withTitle: VPhoneLocalization.text("Set"))+ alert.addButton(withTitle: VPhoneLocalization.text("Cancel"))+ alert.window.initialFirstResponder = field++ VPhoneAlert.present(alert) { [weak self] response in+ guard let self, response == .alertFirstButtonReturn else { return }+ let text = field.stringValue+ guard let udid = VPhoneGuestControl.normalizedUDID(text) else {+ VPhoneAlert.present(+ title: "Invalid UDID",+ message: "Enter 8 and 16 hexadecimal digits joined by a hyphen, or 40 hexadecimal digits.",+ style: .warning,+ ) { [weak self] _ in+ self?.promptForUDID(initial: text)+ }+ return+ }+ applyUDID(udid)+ }+ }++ private func applyUDID(_ udid: String) {+ Task {+ do {+ guard let applied = try await control.setProfileUDID(udid) else {+ throw VPhoneGuestControl.ControlError.protocolError("udid.set returned no UDID")+ }+ VPhoneAlert.present(+ title: "Set UDID",+ message: VPhoneLocalization.format(+ "App installs now check provisioning profiles against %@.",+ applied,+ ),+ style: .informational,+ )+ } catch {+ print("[udid] set failed: \(error)")+ VPhoneAlert.present(+ title: "Unable to Set UDID",+ message: "Check that the guest agent is connected, then try again.",+ style: .warning,+ )+ }+ }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 2bd16fc2..39d008b3 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -202,6 +202,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {mc?.updateClipboardAvailability(available: caps.contains("clipboard"))mc?.updateSettingsAvailability(available: true)mc?.updateRestartAvailability(available: caps.contains("system_control"))+ mc?.updateUDIDAvailability(available: caps.contains("udid_override"))mc?.updatePanelAvailability(capabilities: caps)if caps.contains("location") {mc?.updateLocationCapability(available: true)@@ -228,6 +229,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {mc?.updateClipboardAvailability(available: false)mc?.updateSettingsAvailability(available: false)mc?.updateRestartAvailability(available: false)+ mc?.updateUDIDAvailability(available: false)mc?.updatePanelAvailability(capabilities: [])provider?.stopReplay()provider?.stopForwarding()