Files
Guilherme Rambo aabca5342d Xcode app provisioning (#823)
* Automatic provisioning of Mac apps launched via Xcode

* Improve Xcode integration sheet UI

* Security: harden local debugging socket and Xcode tool usage

* Soften rule around Xcode MCP use and xcodebuild prohibition

* Security: harden App Store Connect API key storage and access

* Fix debugged app incorrectly detected as not provisioned due to wildcard matching in provisioning profile

* Add previews for provisioning and debugging UI elements

* Disambiguate virtual machine vs. host Mac in provisioning and signing team management UIs

* Make Xcode debugging setup accessible from the Guest menu

* Completely disable debugging socket when developer features disabled, fix socket dying on accept failure

* Add versioning to scheme bindings, refer to VirtualBuddy components by a stable symlinked location, store scheme URLs so that app can potentially migrate schemes in the future

* Delay showing provisioning sheet so that an app that's already provisioned for the VM doesn't trigger it
2026-11-24 17:46:23 -03:00

106 lines
5.5 KiB
Swift

import Foundation
/// The only network operations are an exact device lookup and registration of one Mac.
/// Each call reads the team key once, which asks for the user's presence. Later calls on
/// the same value reuse that approval, so keep one value for one user-initiated task.
public struct MacDeviceRegistration: Sendable {
public enum Status: Equatable, Sendable { case enabled, disabled }
/// Takes the team and the reason shown to the user, completing “The app is trying to…”.
private let credential: @Sendable (String, String) async throws -> RegistrationCredential
private let session: URLSession
private static let endpoint = URL(string: "https://api.appstoreconnect.apple.com/v1/devices")!
public init(keys: DeviceRegistrationKeys) {
let configuration = URLSessionConfiguration.ephemeral
configuration.httpShouldSetCookies = false
configuration.urlCredentialStorage = nil
let authentication = RegistrationAuthentication()
self.init(session: URLSession(configuration: configuration)) {
try await keys.credential(for: $0, reason: $1, authentication: authentication)
}
}
init(session: URLSession, credential: @escaping @Sendable (String, String) async throws -> RegistrationCredential) {
self.session = session
self.credential = credential
}
private struct Device: Decodable {
struct Attributes: Decodable { let udid, platform, status: String }
let attributes: Attributes
func status(for udid: String) throws -> Status {
guard attributes.platform == "MAC_OS", attributes.udid == udid else {
throw DeviceRegistrationError("Apple returned a different Mac identifier. Check the registered provisioning UDID.")
}
switch attributes.status {
case "ENABLED": return .enabled
case "DISABLED": return .disabled
default: throw DeviceRegistrationError("Apple reports device status \(attributes.status). Check the device in your developer account.")
}
}
}
private struct Response<Value: Decodable>: Decodable { let data: Value }
private struct ServiceFailure: Decodable {
struct Detail: Decodable { let detail: String? }
let errors: [Detail]
}
private struct HTTPFailure: LocalizedError {
let code: Int
let detail: String?
var errorDescription: String? { "App Store Connect (\(code)). " + (detail ?? HTTPURLResponse.localizedString(forStatusCode: code)) }
}
public func lookup(udid: String, teamID: String) async throws -> Status? {
try await lookup(udid: udid, key: credential(teamID, "check whether the selected device is registered with team \(teamID)"))
}
private func lookup(udid: String, key: RegistrationCredential) async throws -> Status? {
var components = URLComponents(url: Self.endpoint, resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "filter[udid]", value: udid), URLQueryItem(name: "filter[platform]", value: "MAC_OS")]
let data = try await request(URLRequest(url: components.url!), key: key)
let matches = try JSONDecoder().decode(Response<[Device]>.self, from: data).data
return try matches.first?.status(for: udid)
}
/// Call after the user approves consuming a device slot on this team.
public func register(name: String, udid: String, teamID: String) async throws -> Status {
let key = try await credential(teamID, "register “\(name)” with team \(teamID)")
if let existing = try await lookup(udid: udid, key: key) { return existing }
var create = URLRequest(url: Self.endpoint)
create.httpMethod = "POST"
create.setValue("application/json", forHTTPHeaderField: "Content-Type")
create.httpBody = try JSONSerialization.data(withJSONObject: ["data": ["type": "devices", "attributes": [
"name": name, "platform": "MAC_OS", "udid": udid
]]])
do {
let data = try await request(create, key: key)
return try JSONDecoder().decode(Response<Device>.self, from: data).data.status(for: udid)
} catch let failure as HTTPFailure where failure.code == 409 {
// Two hosts can register the same Mac between the lookup and creation.
if let existing = try await lookup(udid: udid, key: key) { return existing }
throw failure
}
}
private func request(_ request: URLRequest, key: RegistrationCredential) async throws -> Data {
var request = request
request.setValue("Bearer " + (try key.token(at: Date())), forHTTPHeaderField: "Authorization")
try Task.checkCancellation()
let (data, response) = try await session.data(for: request, delegate: NoRedirect())
guard let response = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
guard (200..<300).contains(response.statusCode) else {
let failure = try? JSONDecoder().decode(ServiceFailure.self, from: data)
throw HTTPFailure(code: response.statusCode, detail: failure?.errors.first?.detail)
}
return data
}
}
private final class NoRedirect: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(nil)
}
}